您的位置:首页 > 产品设计 > UI/UE

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.

思路:先循环遍历一遍字符,统计出各个字符出现的次数,然后再遍历一遍,找出第一个出现一次的字符索引;

代码:

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 Uniqu