题目地址:
https://www.lintcode.com/problem/unique-characters/description
给定一个字符串,判断其是否有重复字符。直接用哈希表即可。代码如下:
import java.util.HashSet;
import java.util.Set;
public class Solution {
/*
* @param str: A string
* @return: a boolean
*/
public boolean isUnique(String str) {
// write your code here
Set<Character> set = new HashSet<>();
for (int i = 0; i < str.length(); i++) {
// 如果加入失败说明有重复,则返回false
if (!set.add(str.charAt(i))) {
return false;
}
}
return true;
}
}
时空复杂度 O ( n ) O(n) O(n)。