您的位置:首页 > 产品设计 > UI/UE

1.1 Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures.

2015-09-16 15:33 603 查看
思路: 假设给定字符串用的是ASCII编码,那么总共就只有256个字符,新建一个256个元素的boolean数组, 遍历字符串,将出现的字符在boolean数组所在位置置 1。如果碰到已经置一,表明出现重复字符,返回false。

public class IsUniqueChars_1 {

public boolean solu(String s) {
boolean table[] = new boolean[256];
for (int i = 0; i < s.length(); i++) {
int ascii = (int) s.charAt(i);
if (table[ascii])
return false;
else
table[ascii] = true;
}
return true;
}
}


优化:如果字符串长度超过256,肯定出现过重复字符了。这是只要直接返回 false 就行

public class IsUniqueChars_1 {

public boolean solu(String s) {
if (s.length() > 256)
return false;
boolean table[] = new boolean[256];
for (int i = 0; i < s.length(); i++) {
int ascii = (int) s.charAt(i);
if (table[ascii])
return false;
else
table[ascii] = true;
}
return true;
}
}


2015-09-16
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: