原文:
Implement an algorithm to determine if a string has all unique characters.What if you can not use additional data structures?
译文:
实现一个算法来判断一个字符串中的字符是否唯一(即没有重复).不能使用额外的数据结构。(即只使用基本的数据结构)
解答:
空间换时间
哈希表解决:
package com.zhuyu_deng.test;
public class Test
{
static boolean isUniqueChar(String x)
{
boolean check[] = new boolean[256]; // 初始化为false;
for(int i = 0, len = x.length(); i < len; ++i)
{
int index = (int)x.charAt(i);
if (check[index] == true)
return false;
check[index] = true;
}
return true;
}
public static void main(String args[])
{
String s = "abcdefghijklmnopqrstuvwxyzABCD1234567890";
boolean ans = isUniqueChar(s);
System.out.println(ans);
}
}
ps:类似的题目还有下面这个。