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.
题意:找到字符串中没有重复的字符,并且这个字符是第一个出现的。题目已经给出条件:输入的字符全部是小写,所以大小写区分这些问题就不用考虑了。
public class Solution {
public int firstUniqChar(String s) {
/////超时了哈哈哈哈哈哈
// int count,i;
// for(i=0;i<s.length();i++){
// count=0;
// for(int j=0;j<s.length();j++){
// if(s.charAt(i)==s.charAt(j)){
// count++;
// }
// }
// if(count==1)
// return i;
// else
// continue;
// }
// return -1;
int[] hash=new int[26];
for(int i=0;i<s.length();i++){
hash[s.charAt(i)-‘a‘]++;
}
for(int i=0;i<s.length();i++){
if(hash[s.charAt(i)-‘a‘]==1){
return i;
}
}
return -1;
}
}PS:额。。。。。。第一次暴力两层for循环,果然超时。
然后又是统计词频。。。。。。。。。。。。。。。。然后返回去遍历字符串找到第一个次数为1的即可。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
Leetcode 387. First Unique Character in a String JAVA语言
原文:http://fulin0532.blog.51cto.com/6233825/1890911