-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy path[lint]. Unique Characters.java
executable file
·92 lines (74 loc) · 1.79 KB
/
[lint]. Unique Characters.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
E
tags: String, Array, Lint
determine if characters are unique in string
#### HashSet
- space O(n), time O(n)
#### char[]
- space O(n), time O(nlogn)
#### no additional data structure
- double for loop: O(n^2)
```
/*
LintCode
Implement an algorithm to determine if a string has all unique characters.
Example
Given "abc", return true.
Given "aab", return false.
Challenge
What if you can not use additional data structures?
Tags Expand
String Cracking The Coding Interview Array
*/
public class Solution {
public boolean isUnique(String str) {
if (str == null || str.length() == 0) return true;
char[] arr = str.toCharArray(); // nlogn
Arrays.sort(arr);
for (int i = 1; i < arr.length; i++) {
if (arr[i] == arr[i - 1]) return false;
}
return true;
}
}
/*
Thought:
1st, write hasset, there you go.
*/
public class Solution {
public boolean isUnique(String str) {
if (str == null || str.length() == 0) {
return true;
}
HashSet<Character> set = new HashSet<Character>();
for (int i = 0; i < str.length(); i++) {
if (!set.contains(str.charAt(i))) {
set.add(str.charAt(i));
} else {
return false;
}
}//end for
return true;
}
}
/*
Thought:
do it without hash set.
Can do a double-for loop, check from i~j, if str[i] exist later in the string.
O(n^2)
*/
public class Solution {
public boolean isUnique(String str) {
if (str == null || str.length() == 0) {
return true;
}
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j < str.length(); j++) {
if (str.charAt(i) == str.charAt(j)) {
return false;
}
}
}
return true;
}
}
```