1.1 Implement an algorithm to determine if a string has all unique characters .
What if you can not use additional data structures?
1. ASCII string or Unicode string
Unicode used 8,16 or 32 bits to store information whereas ASCII used 7 bits. (or now ASCII becomes 8 bits)
Unicode can represent more than 65000 characters/symbols as compared to ASCII only support 128 characters.
Unicode characters are standardized to represent most of commonly used languages worldwide including asian/indian languages. But ASCII only used for frequent American English encoding. For example ASCII does not use symbol of pound or umlaut.
This is helping in common standard for document genration in any language independent of any custom software using custom mapping of characters.
2. java bit operation
~ invert a bit pattern, can applied to any of the integral types, making every "0" a "1" and every "1" a "0".
<< shift a bit pattern to the left
>> shift a bit pattern to the right
>>> unsigned right shift operator, shift a zero into the leftmost position
& AND operation
^ exclusive OR operation sets the bit to 1
where the corresponding bits in its operands are different, and to 0
if they are the same
can be used to swap two integers without using intermediate.
a ^ = b;
b ^= a;
a ^= b;
| inclusive OR operation
class Unique{
public static boolean isUniqueChar (String str){
if (str.length() > 256)
return false;
boolean[] check = new boolean[256]; // it should be 256 lenght
for (int i=0; i< str.length(); i++){
if (check[str.charAt(i)]){
System.out.println("1.Duplication exists.");
return false;
} else{
check[str.charAt(i)] = true; // set the position of val not i to be true
}
}
System.out.println("1.Every char is unique.");
return true;
}
public static boolean isUniqueChar2 (String str){
if (str.length() > 256)
return false;
int check = 0;
for (int i=0;i<str.length();i++){
int val = str.charAt(i) - 'a';
if ( (check & (1<<val))> 0){ // 将1左移val位
System.out.println("2.Duplication exists.");
return false;
} else{
check |= 1<<val;
}
}
System.out.println("2.Every char is unique.");
return true;
}
public static void main(String[] args){
String str = "abac";
isUniqueChar(str);
isUniqueChar2(str);
}
}