http://www.hawstein.com/posts/1.1.html--原文C++实现
Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?
Java实现:
public class TestDemo01 {
public static void main(String[] args) {
String str = "123rtxhs4567890-=_+<>?LHFCDZWARIJ:Jadclm;./'[";
boolean resultASCII = isUniqueByASCII(str);
System.out.println("resultASCII=" + resultASCII);
boolean resultBit = isUniqueByBit(str);
System.out.println("resultBit=" + resultBit);
}
/**
* 扩展的ASCII只有256个字符,定义一个数组,
* 保存每个字符的状态,可根据每个字符的状态判断是否重复
* @param str
* @return
*/
public static boolean isUniqueByASCII(String str) {
boolean[] tempArray = new boolean[256];
for (int i = 0; i < str.length(); i++) {
int charNum = str.charAt(i);
if (tempArray[charNum] != false) {
return false;
}
tempArray[charNum] = true;
}
return true;
}
/**
* 扩展的ASCII只有256个字符,定义一个8位整形数组,
* 每个整型数可表示32个字符的状态,根据每个字符的状态判断
* @param str
* @return
*/
public static boolean isUniqueByBit(String str) {
int[] tempArr = new int[8];
for (int i = 0; i < str.length(); i++) {
int charNum = str.charAt(i);
int tempArrIndex = charNum / 32;
int tempArrRes = charNum % 32;
if ((tempArr[tempArrIndex] & (1 << tempArrRes)) != 0) {
return false;
}
tempArr[tempArrIndex] |= (1 << tempArrRes);
}
return true;
}
}