现在的位置: 首页 > 综合 > 正文

CCI习题1-1:String Contain Unique Char

2017年12月24日 ⁄ 综合 ⁄ 共 1089字 ⁄ 字号 评论关闭

package question1_1;

/*
 * Implement an algorithm to determine if a string has all unique characters
 */

public class Question {
//位操作
public static boolean isUniqueChars1(String str){
if(str.length()>256){
return false;
}
//字母二进制左移序号val位(例如a 0,c 2)
//字母X与自身X按位与>0,与其他=0
//checker每一位按位或操作,存储字母a~z是否出现过,相应的1对应相应序号的字母出现过
//只要字母X曾经出现过1次,下一次循环按位与>0
int checker=0;
for(int i=0;i<str.length();i++){
int val=str.charAt(i)-'a';
if((checker&(1<<val))>0)
return false;
checker|=(1<<val);
}
return true;
}
//数组存储
public static boolean isUniqueChars(String str) {
if (str.length() > 256) {
return false;
}
boolean[] char_set = new boolean[256];
for (int i = 0; i < str.length(); i++) {
int val = str.charAt(i);
if (char_set[val]) return false;
char_set[val] = true;
}
return true;
}

public static boolean isUniqueChars2(String str){
if (str.length() > 256) {
return false;
}
boolean [] char_set=new boolean[256];
for(int i=0;i<str.length();i++){
int val=str.charAt(i);
if(char_set[val])
return false;
char_set[val]=true;
}
return true;
}

public static void main(String[] args) {
String[] words={"abcde", "hello", "apple", "kite", "padle"};
for(String word:words){
System.out.println(word+":"+isUniqueChars(word)+" "+isUniqueChars2(word));
}
}
}

抱歉!评论已关闭.