Promble:
Implement an algorithm to determine if a string have all unique characters. What if do cannot use addtional data structure?
My Solution:
1.ckeck wether the length of STR is really equal to 0 or more than, if yes, it would return false
2. ASCII has a character
3. Use ToArray function chage string as char array
4. Sort Char Array
5. Compare between-character, get duplicate or not
Code
public static Boolean different (String str) {
if (Str.length () ==0| | str==null| | Str.length () >256) return false;
char[] strlist = Str.tochararray ();
Arrays.sort (strlist);
for (int i= 1; i<strlist.length; i++) {
if (Strlist[i]==strlist[i-1])
return true;
}
return false;
}
The given solution:
1. Build a Boolean Array and record the character appear on the string according the ASCII value
2. If corresponding ASCII value is exist and then return false.
Code
public static Boolean isUniqueChars2 (String str) {
if (Str.length () ==0| | Str.length () >256) return false;
boolean[] Char_set = new boolean[256];
for (int i =0; i < str.length (); i++) {
int value = Str.charat (i)
if (Char_set[value]) {
return false;
}
Char_set[value]=true;
}
return true;
}
Cc150-array and String 1.1