[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 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 字符串的第一个唯一字符的更多相关文章
- LeetCode387First Unique Character in a String字符串中第一个唯一字符
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引.如果不存在,则返回 -1. 案例: s = "leetcode" 返回 0. s = "loveleetcod ...
- LeetCode 387. First Unique Character in a String (字符串中的第一个唯一字符)
题目标签:String, HashMap 题目给了我们一个 string,让我们找出 第一个 唯一的 char. 设立一个 hashmap,把 char 当作 key,char 的index 当作va ...
- 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 ...
- 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 ...
- [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 ...
- 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 ...
- 387 First Unique Character in a String 字符串中的第一个唯一字符
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引.如果不存在,则返回 -1.案例:s = "leetcode"返回 0.s = "loveleetcode&qu ...
- leetcode修炼之路——387. First Unique Character in a String
最近公司搬家了,有两天没写了,今天闲下来了,继续开始算法之路. leetcode的题目如下: Given a string, find the first non-repeating characte ...
- 【LeetCode】387. First Unique Character in a String 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
随机推荐
- 自定义控件LengthValidator
1.创建自定义验证控件:新建LengthValidator类并继承BaseValidator using System; using System.Collections.Generic; using ...
- 《BUG创造队》第四次作业:基于原型的团队项目需求调研与分析
项目 内容 这个作业属于哪个课程 2016级软件工程 这个作业的要求在哪里 实验八 团队作业4:基于原型的团队项目需求调研与分析 团队名称 BUG创造队 作业学习目标 (1)体验以原型设计为基础的团队 ...
- C#锐利体验2读书笔记
匿名方法,迭代,匿名方法允许我们以一种“内联”的方法来编写方法代码;匿名方法是直接与委托实例化相关联的,使委托实例化更加直观方便.匿名方法的几个相关问题--参数列表,--返回值,--外部变量. add ...
- 用Queue控制python多线程并发数量
python多线程如果不进行并发数量控制,在启动线程数量多到一定程度后,会造成线程无法启动的错误. 下面介绍用Queue控制多线程并发数量的方法(python3). # -*- coding: utf ...
- Django REST framework版本控制
参考链接:https://www.cnblogs.com/liwenzhou/p/10269268.html 1.路由: #版本控制 re_path('^(?P<version>[v1|v ...
- Windows10 Faster R-CNN(GPU版) 配置训练自己的模型
参考链接 1. 找到合适自己的版本,下载安装Anaconda 点击跳转下载安装 Anaconda,双击下载好的 .exe 文件安装,只勾选第一个把 conda 添加到 PATH 路径.
- docker 下载安装镜像
docker安装成功后. 1.搜索镜像 # docker search java 可使用 docker search命令搜索存放在 Docker Hub(这是docker官方提供的存放所有docker ...
- SQL基础-创建新的输出字段
一.创建新的输出字段 1.建表.插数据 ### CREATE TABLE `t_stock_trans_dtl` ( `trans_id` varchar(100) NOT NULL COMMENT ...
- 52、Spark Streaming之输入DStream之基础数据源以及基于HDFS的实时wordcount程序
一.概述 1.Socket:之前的wordcount例子,已经演示过了,StreamingContext.socketTextStream() 2.HDFS文件 基于HDFS文件的实时计算,其实就是, ...
- Codeforces Round #595 (Div. 3)
A - Yet Another Dividing into Teams 题意:n个不同数,分尽可能少的组,要求组内没有两个人的差恰为1. 题解:奇偶分组. int a[200005]; void te ...