LeetCode:First Unique Character in a String
2016-08-31 00:00
435 查看
摘要: 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.
思路:先循环遍历一遍字符,统计出各个字符出现的次数,然后再遍历一遍,找出第一个出现一次的字符索引;
代码:
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
思路:先循环遍历一遍字符,统计出各个字符出现的次数,然后再遍历一遍,找出第一个出现一次的字符索引;
代码:
public int firstUniqChar(String s) { if (s == null || s.length() < 0) { return -1; } if (s.length() == 1) { return 0; } //用来统计字符出现的次数 Map<Character, Integer> map = new HashMap<Character, Integer>(); //首先循环遍历一次,统计出各个字符出现的次数 for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (!map.containsKey(c)) { map.put(c, 1); }else { map.put(c, map.get(c)+1);//如果在map中存在该字符了,则次数+1; } } //再循环遍历一遍,找出只出现一次的那个字符索引 for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (map.get(c) == 1) { return i; } } return -1; }
相关文章推荐
- Leetcode算法比赛----First Unique Character in a String
- LeetCode: First Unique Character in a String
- leetcode:First Unique Character in a String
- 【LeetCode-387】First Unique Character in a String(C++)
- leetcode_387 First Unique Character in a String
- [Leetcode]First Unique Character in a String
- Leetcode 387 First Unique Character in a String
- LeetCode-First Unique Character in a String
- leetcode---First Unique Character in a String
- LeetCode 387:First Unique Character in a String
- 【LeetCode】387 First Unique Character in a String(java实现)
- [LeetCode] First Unique Character in a String(Java)
- [LeetCode] First Unique Character in a String 字符串第一个不同字符
- Leetcode: First Unique Character in a String
- leetcode387:First Unique Character in a String
- LeetCode(387)First Unique Character in a String
- 384.[LeetCode]First Unique Character in a String
- leetcode 387 First Unique Character in a String C++
- [Leetcode] First Unique Character in a String
- leetcode First Unique Character in a String