I just begin to do the problems in cracking the coding interview. this is the first question: implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? Here is the solution: Using a boolean array to track the occurrence of each possible character in ASCII set. Initially every value in that array is false, until the corresponding character value appears. If that character value appears again, then if the corresponding value in array is already true, return false. Time: O(n), n is the length of string. Space: O(n), the array named mask. Source Code:
public class Interview {
// Assume every character in string is in ASCII.
public boolean uniqueChars(String s) {
boolean[] mask = new boolean[256];
for (int i = 0; i < s.length(); i++) {
if (mask[s.charAt(i)])
return false;
mask[s.charAt(i)] = true;
}
return true;
}
}
I cannot understand this: mask[s.charAt(i)]. I think s.charAt(i) is a char but not a number, so I am don't know how this works. I know this is a simply question, but I cannot find a direct answer. Hope you guys can help me.Thanks a lot.