1.1 Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?
这个题主要操作集中在查找上面,所以首先想到的就是哈希,时间复杂度为O(n);字符不超过256,定义256大小的数组就ok了。书上指出的其他方法还有O(n^2)的蛮力查找;O(nlogn)排序然后检查是否有相同。
package Question1_1;
import java.util.HashSet;
import java.util.Set;
public class Question1_1
{
public static void main(String[] args)
{
Question1_1 q = new Question1_1();
String[] testStrings = {"abcdefg", "abcdefe", "1234e;z.", "32,./??'"};
for (String x : testStrings)
System.out.print(q.CheckUniqueChar1(x) + " ");
System.out.println();
for (String x : testStrings)
System.out.print(q.CheckUniqueChar2(x) + " ");
}
/*
* Using hash table data structure
*/
public boolean CheckUniqueChar1(String s)
{
Set<Character> set = new HashSet<Character>();
int i;
for (i = 0; i < s.length(); i++)
if (!set.contains(s.charAt(i))) set.add(s.charAt(i));
else return false;
return true;
}
/*
* Without using hash table, but essentially the same implementation
*/
public boolean CheckUniqueChar2(String s)
{
// char variable (ASCII) cannot exceed 256
boolean[] chars = new boolean[256];
int i;
// if chars[s.charAt(i)] == false, then it hasn't occurred ever
for (i = 0; i < s.length(); i++)
if (chars[s.charAt(i)] == false) chars[s.charAt(i)]= true;
else return false;
return true;
}
}
PS:快速排序方法:
/*
* Using quick sort
*/
public boolean CheckUniqueChar3(String a)
{
char[] s = a.toCharArray();
return CheckUniqueChar3Helper(s, 0, s.length - 1);
}
private boolean CheckUniqueChar3Helper(char[] s, int left, int right)
{
// choose the left element as pivot for simplicity
if (left > right)
return true;
int p = s[left];
// partition around p
int i, j;
for (i = left + 1, j = left + 1; j <= right; j++)
{
if (p > s[j])
{
char temp = s[i];
s[i++] = s[j];
s[j] = temp;
}
else if (p == s[j])
{
return false;
}
}
char temp = s[i-1];
s[i-1] = s[left];
s[left] = temp;
// recursive call
if (CheckUniqueChar3Helper(s, left, i-2) == false)
return false;
if (CheckUniqueChar3Helper(s, i, right) == false)
return false;
return true;
}
}