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. python——selenium库的使用

    selenium 是一个用于Web应用程序测试的工具.Selenium测试直接运行在浏览器中,就像真正的用户在操作一样.支持的浏览器包括IE(7, 8, 9, 10, 11),Mozilla Fire ...

  2. Python练习——约瑟夫环问题、用类方法描述一个数字时钟

    一.约瑟夫环问题 有15个基督徒和15个非基督徒在海上遇险,为了能让一部分人活下来不得不将其中15个人扔到海里面去,有个人想了个办法就是大家围成一个圈,由某个人开始从1报数,报到9的人就扔到海里面,他 ...

  3. less-5

    首先输入id=1和id=1’未报错,均显示You are in.....(如下图所示) 由上图可以看到,如果运行返回结果正确的时候只返回you are in...,不会返回数据库当中的信息了,所以我们 ...

  4. tf.logging.set_verbosity

    tf.logging.set_verbosity (tf.logging.INFO) 作用:将 TensorFlow 日志信息输出到屏幕

  5. 【游记】CSP2019 垫底记

    考试时候的我: Day 1 做完 \(T1\) 和 \(T2\),还有 \(2.5 h\),我想阿克 \(Day1\).(\(T3\):不,你不想) 不过一会就想出来给每个点 dfs 贪心选一个点,然 ...

  6. HDU 2887 Watering Hole(MST + 倍增LCA)

    传送门 总算是做上一道LCA的应用题了... 题意:有$n$个牧场, $m$根管道分别连接编号为$u,v$的牧场花费$p_{i}$,在第$i$个牧场挖口井需要花费$w_{i}$,有$P$根管道直接连通 ...

  7. file 的类型 input

    上传你选择的文件和相关信息.在 HTML 文档中 <input type="file"> 标签每出现一次,一个 FileUpload 对象就会被创建.该元素包含一个文本 ...

  8. dinoql 使用graphql 语法查询javascript objects

    dinoql 是一个不错的基于graphql 语法查询javascript objects 的工具包,包含以下特性 graphql 语法(很灵活) 安全的访问(当keys 不存在的时候,不会抛出运行时 ...

  9. 3-ESP8266 SDK开发基础入门篇--点亮一个灯

    https://www.cnblogs.com/yangfengwu/p/11072834.html 所有的源码 https://gitee.com/yang456/Learn8266SDKDevel ...

  10. 洛谷P1816 忠诚 题解

    洛谷P1816 忠诚 题解 题目描述 老管家是一个聪明能干的人.他为财主工作了整整10年,财主为了让自已账目更加清楚.要求管家每天记k次账,由于管家聪明能干,因而管家总是让财主十分满意.但是由于一些人 ...