35 第一次只出现一次的字符

在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置

C++:

 1 class Solution {
 2 public:
 3     int FirstNotRepeatingChar(string str) {
 4         int hash[256] = {0} ;
 5         for(char c : str){
 6             hash[c]++ ;
 7         }
 8         for(int i = 0 ; i < str.size() ; i++){
 9             if (hash[str[i]] == 1)
10                 return i ;
11         }
12         return -1 ;
13     }
14 };

字符出现0次,状态为00

字符出现1次,状态为10

字符出现2次及2次以上,状态为11

java:

 1 public int FirstNotRepeatingChar(String str) {
 2     BitSet bs1 = new BitSet(256);
 3     BitSet bs2 = new BitSet(256);
 4     for (char c : str.toCharArray()) {
 5         if (!bs1.get(c) && !bs2.get(c))
 6             bs1.set(c);     
 7         else if (bs1.get(c) && !bs2.get(c))
 8             bs2.set(c);     
 9     }
10     for (int i = 0; i < str.length(); i++) {
11         char c = str.charAt(i);
12         if (bs1.get(c) && !bs2.get(c))
13             return i;
14     }
15     return -1;
16 }

猜你喜欢

转载自www.cnblogs.com/mengchunchen/p/9019937.html