# 面试：字符串中的相关试题


//如果字符集只是a－z(或是A－Z)，那就更好办了，用位运算只需要一个整型数即可。
public static boolean stringDiff(String str) {
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;
}

//bool数组实现
public static boolean stringDiff2(String str) {
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;
}

//int数组，位表示
public static boolean stringDiff(String string) {
int[] a = new int[8];
int len = string.length();
for(int i=0; i < len; ++i) {
int v = (int)string.charAt(i);
int idx = v / 32;
int shift = v % 32;
if((a[idx] & (1 << shift)) > 0) return false;
a[idx] |= (1 << shift);
}
return true;
}


• 引入TreeSet：通过集合快速找到所有出现的字符串
• 引入ArrayList：为了快速排序，再通过StringBuilder生成排序后的字符串
• 通过String API中的基本方法indexOf，lastIndexOf来计算TreeSet中每个字符串的最大值
    public static void doString(String input) {
char[] charArr = input.toCharArray();
List list = new ArrayList();
TreeSet set = new TreeSet();
for(int i = 0; i < charArr.length; i++) {
}
System.out.println(set);
Collections.sort(list);
System.out.println(list);

StringBuilder sb = new StringBuilder();
for(int i = 0; i < list.size(); i++) {
sb.append(list.get(i));
}
input = sb.toString();
System.out.println(input);

int maxNum = 0;
String maxString = "";
List maxList = new ArrayList();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
String str = iterator.next().toString();
int startIndex = input.indexOf(str);
int lastIndex = input.lastIndexOf(str);
int tempMax = lastIndex - startIndex + 1;
if(tempMax > maxNum) {
maxNum = tempMax;
maxString = str;
} else if(tempMax == maxNum) {
}
}

int index = 0;
for(int i = 0; i < maxList.size(); i++) {
if(maxList.get(i).equals(maxString)) {
index = i;
break;
}
}

System.out.println("max data: ");

for(int i = index; i < maxList.size(); i++) {
System.out.print(maxList.get(i) + " ");
}

System.out.println();
System.out.println("max: " + maxNum);
}


posted @ 2017-03-27 10:17  Farnear  阅读(344)  评论(0编辑  收藏  举报