Skip to content

Commit b59b41f

Browse files
committed
First Unique Character in a String: Optimize
1 parent d5a2bf6 commit b59b41f

File tree

3 files changed

+8
-43
lines changed

3 files changed

+8
-43
lines changed

LeetCodePrj/Java/leetcode/easy/page2/EasyPage2.java

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -62,12 +62,6 @@ public void testIsPerfectSquare() {
6262
validPerfectSquare.isPerfectSquare(5);
6363
}
6464

65-
@Test
66-
public void testFirstUniqueCharacterInAString() {
67-
FirstUniqueCharacterInAString firstUniqueCharacterInAString = new FirstUniqueCharacterInAString();
68-
firstUniqueCharacterInAString.firstUniqChar("leetcode");
69-
}
70-
7165
@Test
7266
public void testFindTheDifference() {
7367
FindTheDifference findTheDifference = new FindTheDifference();

LeetCodePrj/Java/leetcode/easy/page2/FirstUniqueCharacterInAString.java

Lines changed: 0 additions & 19 deletions
This file was deleted.

LeetCodePrj/Java/leetcode/easy/page3/FirstUniqueCharacterInAString.java

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,29 +4,19 @@
44

55
public class FirstUniqueCharacterInAString {
66

7-
private int[] alpha = new int[128];
8-
private int[] initPos = new int[128];
9-
107
public int firstUniqChar(String s) {
11-
PriorityQueue<Integer> pos = new PriorityQueue<>();
12-
13-
char[] chars = s.toCharArray();
8+
int[] countArr = new int[26];
149

15-
for (int i = 0; i < chars.length; i++) {
16-
alpha[chars[i]]++;
10+
for (char c : s.toCharArray()) {
11+
countArr[c - 97]++;
12+
}
1713

18-
if (alpha[chars[i]] == 1) {
19-
pos.offer(i);
20-
initPos[chars[i]] = i;
21-
} else if (alpha[chars[i]] == 2) {
22-
pos.remove(initPos[chars[i]]);
14+
for (int i = 0; i < s.length(); i++) {
15+
if (countArr[s.charAt(i) - 97] == 1) {
16+
return i;
2317
}
2418
}
2519

26-
if (pos.isEmpty()) {
27-
return -1;
28-
} else {
29-
return pos.poll();
30-
}
20+
return -1;
3121
}
3222
}

0 commit comments

Comments
 (0)