ASCII char set in Java
问题出在破解代码中Interview:实现一种算法来确定字符串是否具有所有唯一字符。这是解决方案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class ASCII { public static boolean isUnique (String str) { boolean[] charSet = new boolean[256]; for (int i = 0; i < str.length(); i++) { int val = str.charAt(i); if (charSet[val]) { return false; } charSet[val] = true; } return true; } public static void main(String[] args) { String[] words = {"abcde","hello"}; for (String word : words) { System.out.println(word +":" + isUnique(word)); } } } |
我有一个非常基本的问题,为什么要创建长度为256的charSet?因为基于ASCII图表(http://www.techonthenet.com/ascii/chart.php),我认为我们只需要127个数字即可表示所有字符。谢谢!
因为存在扩展的ASCII
http://en.wikipedia.org/wiki/Extended_ASCII
128-255代码编码区域性特定字符。
如果要考虑所有Unicode值,则应执行以下操作:
1 |
代替当前的操作。
我也在研究这个问题,并且有同样的问题。这是解决方案
1 2 3 4 5 6 7 8 9 10 11 12 | if (str.length() > 128) { return false; } boolean[] char_set = new boolean[128]; 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; } |
此解决方案不正确。 Java字符串可以使用65536个字符。面试问题不说关于ASCII