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

Examples:

  1. s = "leetcode"
  2. return 0.
  3.  
  4. s = "loveleetcode",
  5. 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

  1. class Solution {
  2. public static int firstUniqChar(String s){
  3. for (int i = 0; i < s.length(); i++) {
  4. boolean isUnique = true;
  5. for (int j = 0; j < s.length(); j++) {
  6. if (i != j && s.charAt(i) == s.charAt(j)){
  7. isUnique = false;
  8. break;
  9. }
  10. }
  11. if (isUnique) return i;
  12. }
  13. return -1;
  14. }
  15. }  

Java:

  1. class Solution {
  2. public int firstUniqChar(String s){
  3. Map<Character, Integer> charMap = new HashMap<>(s.length()); //预先分配大小,避免扩容性能影响
  4. for (int i = 0; i < s.length(); i++) {
  5. if (!charMap.containsKey(s.charAt(i))){
  6. charMap.put(s.charAt(i), 1);
  7. }else {
  8. charMap.put(s.charAt(i), charMap.get(s.charAt(i))+1);
  9. }
  10. }
  11.  
  12. for (int i = 0; i < s.length(); i++) {
  13. if (charMap.get(s.charAt(i)) == 1){
  14. return i;
  15. }
  16. }
  17. return -1;
  18. }
  19. }  

Java:

  1. public class Solution {
  2. public int firstUniqChar(String s) {
  3. char[] array = s.toCharArray();
  4. int[] a = new int[26];
  5. for(int i=0;i<s.length();i++)a[array[i]-'a']++;
  6. for(int i=0;i<s.length();i++){
  7. if(a[array[i]-'a']==1){
  8. return i;
  9. }
  10. }
  11. return -1;
  12. }
  13. }

Java:

  1. class Solution {
  2. public int firstUniqChar(string s) {
  3. vector<int> count(26);
  4. for(int i=0;i<s.size();i++)
  5. count[s[i]-'a']++;
  6. for(int i=0;i<s.size();i++)
  7. if(count[s[i]-'a']==1)
  8. return i;
  9. return -1;
  10. }
  11. }

Java:  

  1. class Solution {
  2. public int firstUniqChar(String s) {
  3. for(int i = 0; i<s.length(); i++) {
  4. if(s.lastIndexOf(s.charAt(i))==s.indexOf(s.charAt(i))) return i;
  5. }
  6. return -1;
  7. }
  8. }  

Python:

  1. class Solution(object):
  2. def firstUniqChar(self, s):
  3. """
  4. :type s: str
  5. :rtype: int
  6. """
  7. letters = {}
  8. for c in s:
  9. if c in letters:
  10. letters[c] = letters[c] + 1
  11. else:
  12. letters[c] = 1
  13. for i in xrange(len(s)):
  14. if letters[s[i]] == 1:
  15. return i
  16. return -1  

Python: 162ms

  1. from collections import defaultdict
  2.  
  3. class Solution(object):
  4. def firstUniqChar(self, s):
  5. """
  6. :type s: str
  7. :rtype: int
  8. """
  9. lookup = defaultdict(int)
  10. candidtates = set()
  11. for i, c in enumerate(s):
  12. if lookup[c]:
  13. candidtates.discard(lookup[c])
  14. else:
  15. lookup[c] = i+1
  16. candidtates.add(i+1)
  17.  
  18. return min(candidtates)-1 if candidtates else -1

Python: 92ms

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

Python: 75ms

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

Python: 60ms

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

C++:

  1. class Solution {
  2. public:
  3. int firstUniqChar(string s) {
  4. unordered_map<char, int> m;
  5. for (char c : s) ++m[c];
  6. for (int i = 0; i < s.size(); ++i) {
  7. if (m[s[i]] == 1) return i;
  8. }
  9. return -1;
  10. }
  11. };

  

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. 自定义控件LengthValidator

    1.创建自定义验证控件:新建LengthValidator类并继承BaseValidator using System; using System.Collections.Generic; using ...

  2. 《BUG创造队》第四次作业:基于原型的团队项目需求调研与分析

    项目 内容 这个作业属于哪个课程 2016级软件工程 这个作业的要求在哪里 实验八 团队作业4:基于原型的团队项目需求调研与分析 团队名称 BUG创造队 作业学习目标 (1)体验以原型设计为基础的团队 ...

  3. C#锐利体验2读书笔记

    匿名方法,迭代,匿名方法允许我们以一种“内联”的方法来编写方法代码;匿名方法是直接与委托实例化相关联的,使委托实例化更加直观方便.匿名方法的几个相关问题--参数列表,--返回值,--外部变量. add ...

  4. 用Queue控制python多线程并发数量

    python多线程如果不进行并发数量控制,在启动线程数量多到一定程度后,会造成线程无法启动的错误. 下面介绍用Queue控制多线程并发数量的方法(python3). # -*- coding: utf ...

  5. Django REST framework版本控制

    参考链接:https://www.cnblogs.com/liwenzhou/p/10269268.html 1.路由: #版本控制 re_path('^(?P<version>[v1|v ...

  6. Windows10 Faster R-CNN(GPU版) 配置训练自己的模型

    参考链接 1. 找到合适自己的版本,下载安装Anaconda 点击跳转下载安装 Anaconda,双击下载好的 .exe 文件安装,只勾选第一个把 conda 添加到 PATH 路径.

  7. docker 下载安装镜像

    docker安装成功后. 1.搜索镜像 # docker search java 可使用 docker search命令搜索存放在 Docker Hub(这是docker官方提供的存放所有docker ...

  8. SQL基础-创建新的输出字段

    一.创建新的输出字段 1.建表.插数据 ### CREATE TABLE `t_stock_trans_dtl` ( `trans_id` varchar(100) NOT NULL COMMENT ...

  9. 52、Spark Streaming之输入DStream之基础数据源以及基于HDFS的实时wordcount程序

    一.概述 1.Socket:之前的wordcount例子,已经演示过了,StreamingContext.socketTextStream() 2.HDFS文件 基于HDFS文件的实时计算,其实就是, ...

  10. Codeforces Round #595 (Div. 3)

    A - Yet Another Dividing into Teams 题意:n个不同数,分尽可能少的组,要求组内没有两个人的差恰为1. 题解:奇偶分组. int a[200005]; void te ...