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. C#将文件转成16进制码流写入数据库存起来,访问的时候再还原成PDF文件。

    转自https://blog.csdn.net/liubowei_0312/article/details/53378146 适合将文件写入数据库,远程访问的时候还原1.首先把文件转成十六进制文件流 ...

  2. adb命令过滤w级别日志命令

    adb logcat *:W 过滤某关键字日志 adb logcat *:W | find "woyihome" 过滤某关键字日志,生成txt文档 adb logcat *:W | ...

  3. 2019-2020-1 20199301《Linux内核原理与分析》第九周作业

    第八章 进程的切换和系统的一般执行过程 进程的调度实际与进程的切换 ntel定义的中断类型 硬中断:就是CPU的两根引脚(可屏蔽中断和不可屏蔽中断) 软中断/异常:包括除零错误.系统调用.调试断点等在 ...

  4. 【Selenium-WebDriver实战篇】ScreenRecorder的实际输出路径,自己的解决方案

    ==================================================================================================== ...

  5. 吉首大学2019年程序设计竞赛(重现赛)D - 数列求和(嘤雄难度)

    链接:https://ac.nowcoder.com/acm/contest/992/D $a_{i}=\dfrac {3a_{i-1}-a_{i-2}}{2}+i+1$ 移项再化一下 $a_{i}- ...

  6. Java 用Jackson进行json和object之间的转换(并解决json中存在新增多余字段的问题)

    1.添加jackson库 如果是maven工程,需要在pom.xml中添加jackson的依赖: <dependency>      <groupId>com.fasterxm ...

  7. [RN] React Native 常见基本问题归纳总结

    [RN] React Native  常见基本问题归纳总结 本问题总结涉及到版本为: "react": "16.8.3","react-native& ...

  8. 关于html异步加载外部json文件报错问题

    一. HTML代码如下: 参考网站(echarts-JSON请求数据):https://blog.csdn.net/you23hai45/article/details/51585506 <!D ...

  9. ubuntu之路——day13 只用python的numpy在较为底层的阶段实现单隐含层神经网络

    首先感谢这位博主整理的Andrew Ng的deeplearning.ai的相关作业:https://blog.csdn.net/u013733326/article/details/79827273 ...

  10. session机制,浏览器禁用cookie后,怎么使用session

    sessionid是存储在cookie中的,解决方案如下: Session URL重写,保证在客户端禁用或不支持COOKIE时,仍然可以使用Session session机制.session机制是一种 ...