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. 【Difference Between Primes HDU - 4715】【素数筛法打表+模拟】

    这道题很坑,注意在G++下提交,否则会WA,还有就是a或b中较大的那个数的范围.. #include<iostream> #include<cstdio> #include&l ...

  2. Manthan, Codefest 19 (open for everyone, rated, Div. 1 + Div. 2)-C. Magic Grid-构造

    Manthan, Codefest 19 (open for everyone, rated, Div. 1 + Div. 2)-C. Magic Grid-构造 [Problem Descripti ...

  3. 使用python的jira库操作jira的版本单和问题单链接

    操作JIRA的API来实现的. 但感觉比单纯操作API要简单一些. from jira import JIRA from django.conf import settings JIRA_URL = ...

  4. CentOS7.5环境下搭建禅道

    在安装配置禅道之前,可以百度了解一下两款项目管理工具禅道与JIRA的区别. 一.安装 进入禅道官网https://www.zentao.net,选择适用的版本进行安装,我这里下载的是“开源版11.6” ...

  5. 如何使用git,进行项目的管理

    1.首先,现在git上个创建一个项目, 2.然后在本地创建一个springboot工程 3.使用git命令   git init 将这个springboot项目交给git进行管理 4.创建一个dev分 ...

  6. switch表达式可使用的类型

    在java中switch后的表达式的类型只能为以下几种:byte.short.char.int(在Java1.6中是这样),在java1.7后支持了对string的判断.

  7. 深度学习Keras框架笔记之AutoEncoder类

    深度学习Keras框架笔记之AutoEncoder类使用笔记 keras.layers.core.AutoEncoder(encoder, decoder,output_reconstruction= ...

  8. python开发笔记-变长字典Series的使用

    Series的基本特征: 1.类似一维数组的对象 2.由数据和索引组成 import pandas as pd >>> aSer=pd.Series([1,2.0,'a']) > ...

  9. ZOJ - 3157:Weapon (几何 逆序对)

    pro:给定平面上N条直线,保证没有直线和Y轴平行. 求有多少交点的X坐标落在(L,R)开区间之间,注意在x=L或者R处的不算. sol:求出每条直线与L和R的交点,如果A直线和B直线在(L,R)相交 ...

  10. WinDbg常用命令系列---||(系统状态)

    ||(系统状态) 简介 双竖线 ( || ) 命令将打印指定的系统或当前正在调试的所有系统的状态. 使用形式 || System 参数 System 指定要显示的系统. 如果省略此参数,将显示正在调试 ...