https://www.lintcode.com/problem/157/
# Description
Implement an algorithm to determine if a string has all unique characters.
# Example
Example 1:
Input: "abc_____"
Output: false
Example 2:
Input: "abc"
Output: true
Challenge
What if you can not use extra space?
# Code
HashSet - O(n) Space
public class Solution { | |
/** | |
* @param str: A string | |
* @return: a boolean | |
*/ | |
public boolean isUnique(String str) { | |
Set<Character> set = new HashSet<>(); | |
for (int i = 0; i < str.length(); i++) { | |
if (set.contains(str.charAt(i))) { | |
return false; | |
} else { | |
set.add(str.charAt(i)); | |
} | |
} | |
return true; | |
} | |
} |
使用 map 記錄位置 O (1) space
public class Solution { | |
/** | |
* @param str: A string | |
* @return: a boolean | |
*/ | |
public boolean isUnique(String str) { | |
boolean[] word = new boolean[256]; | |
for (int i = 0; i < str.length(); i++) { | |
if (word[str.charAt(i)]) return false; | |
word[str.charAt(i)] = true; | |
} | |
return true; | |
} | |
} |