Given a string and a number k, find the k’th non-repeating character in the string. Consider a large input string with millions of characters and a small character set. How can you find the character by doing only one traversal of the input string?
classSolution {
public:staticconstint MAX_CHAR =256;
charkthNonRepeating(const std::string& s, int k) {
int n = s.size();
int count[MAX_CHAR] = {0};
int index[MAX_CHAR];
for (int i =0; i < MAX_CHAR; ++i) index[i] = n;
for (int i =0; i < n; ++i) {
unsignedchar x = s[i];
count[x]++;
if (count[x] ==1) index[x] = i;
if (count[x] ==2) index[x] = n;
}
std::sort(index, index + MAX_CHAR);
return (k >0&& index[k-1] != n) ? s[index[k-1]] :'\0';
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
staticfinalint MAX_CHAR = 256;
publiccharkthNonRepeating(String str, int k) {
int n = str.length();
int[] count =newint[MAX_CHAR];
int[] index =newint[MAX_CHAR];
Arrays.fill(index, n);
for (int i = 0; i < n; i++) {
char x = str.charAt(i);
count[x]++;
if (count[x]== 1) index[x]= i;
if (count[x]== 2) index[x]= n;
}
Arrays.sort(index);
return (k > 0 && index[k-1]!= n) ? str.charAt(index[k-1]) : '\0';
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defkth_non_repeating(self, s: str, k: int) -> str:
MAX_CHAR =256 n = len(s)
count = [0] * MAX_CHAR
index = [n] * MAX_CHAR
for i, ch in enumerate(s):
x = ord(ch)
count[x] +=1if count[x] ==1:
index[x] = i
if count[x] ==2:
index[x] = n
index.sort()
return s[index[k-1]] if k >0and index[k-1] != n else''