Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

Examples:

s = "leetcode"
return 0. s = "loveleetcode",
return 2.

Note: You may assume the string contain only lowercase letters.

给一个字符串,找出第一个不重复的字符,返回它的index,如果不存在,返回-1。假设字符都是小写字母。

解法1: 暴力搜索, T:O(n^2)

解法2: HashMap,第一次遍历每一个字符,统计每种字符出现的次数。第二次遍历,找到第一出现的字符次数为1的字符。

解法3: int [26]数组,由于只有26个字母,所以可以用数组来统计出现的个数。

解法4: 循环26个字母,统计每个字母出现次数为1的字母,写入按出现的index排序的数组。然后取数组里最前面的那个或者为空时是-1

Java: Brute Force

class Solution {
public static int firstUniqChar(String s){
for (int i = 0; i < s.length(); i++) {
boolean isUnique = true;
for (int j = 0; j < s.length(); j++) {
if (i != j && s.charAt(i) == s.charAt(j)){
isUnique = false;
break;
}
}
if (isUnique) return i;
}
return -1;
}
}  

Java:

class Solution {
public int firstUniqChar(String s){
Map<Character, Integer> charMap = new HashMap<>(s.length()); //预先分配大小,避免扩容性能影响
for (int i = 0; i < s.length(); i++) {
if (!charMap.containsKey(s.charAt(i))){
charMap.put(s.charAt(i), 1);
}else {
charMap.put(s.charAt(i), charMap.get(s.charAt(i))+1);
}
} for (int i = 0; i < s.length(); i++) {
if (charMap.get(s.charAt(i)) == 1){
return i;
}
}
return -1;
}
}  

Java:

public class Solution {
public int firstUniqChar(String s) {
char[] array = s.toCharArray();
int[] a = new int[26];
for(int i=0;i<s.length();i++)a[array[i]-'a']++;
for(int i=0;i<s.length();i++){
if(a[array[i]-'a']==1){
return i;
}
}
return -1;
}
}

Java:

class Solution {
public int firstUniqChar(string s) {
vector<int> count(26);
for(int i=0;i<s.size();i++)
count[s[i]-'a']++;
for(int i=0;i<s.size();i++)
if(count[s[i]-'a']==1)
return i;
return -1;
}
}

Java:  

class Solution {
public int firstUniqChar(String s) {
for(int i = 0; i<s.length(); i++) {
if(s.lastIndexOf(s.charAt(i))==s.indexOf(s.charAt(i))) return i;
}
return -1;
}
}  

Python:

class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
letters = {}
for c in s:
if c in letters:
letters[c] = letters[c] + 1
else:
letters[c] = 1
for i in xrange(len(s)):
if letters[s[i]] == 1:
return i
return -1  

Python: 162ms

from collections import defaultdict

class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
lookup = defaultdict(int)
candidtates = set()
for i, c in enumerate(s):
if lookup[c]:
candidtates.discard(lookup[c])
else:
lookup[c] = i+1
candidtates.add(i+1) return min(candidtates)-1 if candidtates else -1

Python: 92ms

class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
return min([s.find(c) for c in 'abcdefghijklmnopqrstuvwxyz' if s.count(c)==1] or [-1])

Python: 75ms

class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
return min([s.find(c) for c in string.ascii_lowercase if s.count(c)==1] or [-1])  

Python: 60ms

def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
""" letters='abcdefghijklmnopqrstuvwxyz'
index=[s.index(l) for l in letters if s.count(l) == 1]
return min(index) if len(index) > 0 else -1 

C++:

class Solution {
public:
int firstUniqChar(string s) {
unordered_map<char, int> m;
for (char c : s) ++m[c];
for (int i = 0; i < s.size(); ++i) {
if (m[s[i]] == 1) return i;
}
return -1;
}
};

  

All LeetCode Questions List 题目汇总

[LeetCode] 387. First Unique Character in a String 字符串的第一个唯一字符的更多相关文章

  1. LeetCode387First Unique Character in a String字符串中第一个唯一字符

    给定一个字符串,找到它的第一个不重复的字符,并返回它的索引.如果不存在,则返回 -1. 案例: s = "leetcode" 返回 0. s = "loveleetcod ...

  2. LeetCode 387. First Unique Character in a String (字符串中的第一个唯一字符)

    题目标签:String, HashMap 题目给了我们一个 string,让我们找出 第一个 唯一的 char. 设立一个 hashmap,把 char 当作 key,char 的index 当作va ...

  3. LeetCode 387. First Unique Character in a String

    Problem: Given a string, find the first non-repeating character in it and return it's index. If it d ...

  4. 18. leetcode 387. First Unique Character in a String

    Given a string, find the first non-repeating character in it and return it's index. If it doesn't ex ...

  5. [leetcode]387. First Unique Character in a String第一个不重复字母

    Given a string, find the first non-repeating character in it and return it's index. If it doesn't ex ...

  6. Java [Leetcode 387]First Unique Character in a String

    题目描述: Given a string, find the first non-repeating character in it and return it's index. If it does ...

  7. 387 First Unique Character in a String 字符串中的第一个唯一字符

    给定一个字符串,找到它的第一个不重复的字符,并返回它的索引.如果不存在,则返回 -1.案例:s = "leetcode"返回 0.s = "loveleetcode&qu ...

  8. leetcode修炼之路——387. First Unique Character in a String

    最近公司搬家了,有两天没写了,今天闲下来了,继续开始算法之路. leetcode的题目如下: Given a string, find the first non-repeating characte ...

  9. 【LeetCode】387. First Unique Character in a String 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

随机推荐

  1. js 预解析以及变量的提升

    js在执行之前会进行预解析. 什么叫预解析? 预:提前 解析:编译 预解析通俗的说:js在执行代码之前会读取js代码,会将变量声明提前. 变量声明包含什么?1.var 声明 2.函数的显示声明. 提前 ...

  2. sql中如何获取一条数据中所有字段的名称和值

    declare ) ) --获取表的列名 ,),filename INTO #templist FROM (select cl.name as filename from sys.tables AS ...

  3. P1505 [国家集训队]旅游[树剖]

    题目描述 Ray 乐忠于旅游,这次他来到了T 城.T 城是一个水上城市,一共有 N 个景点,有些景点之间会用一座桥连接.为了方便游客到达每个景点但又为了节约成本,T 城的任意两个景点之间有且只有一条路 ...

  4. 35 Top Open Source Companies

    https://www.datamation.com/open-source/35-top-open-source-companies-1.html If you think of open sour ...

  5. python变量选中后高亮显示

    file>settings>editor>color scheme>general>code>identifier under caret>backgroun ...

  6. LeetCode 1004. Max Consecutive Ones III

    原题链接在这里:https://leetcode.com/problems/max-consecutive-ones-iii/ 题目: Given an array A of 0s and 1s, w ...

  7. 使用go-mysql-server 开发自己的mysql server

    go-mysql-server是一个golang 的mysql server 协议实现包,使用此工具我们可以用来做好多方便的东西 基于mysql 协议暴露自己的本地文件为sql 查询 基于mysql ...

  8. If...else 条件判断和If else嵌套

    If(条件表达式){ 如果条件表达式结果为true,执行该处代码. 如果条件表达式结果为false,执行下边代码. }else{ 如果条件表达式结果为false,执行该处代码. } If(条件表达式) ...

  9. 【NOIP2015】真题回顾

    题目链接 神奇的幻方 按照题意模拟 信息传递 不难想到这是一个基环树的森林,找一个最小环就可以了 斗地主 毒瘤搜索题,时限不紧,但是要考虑全所有情况 需要注意的一些地方: 先枚举顺子.再枚举四带二.三 ...

  10. Matlab下的文件执行路径

    Matlab下有时命令出错,源于Command窗口的路径不正确.快捷键的执行会受此影响.