# 387. First Unique Character in a String#2(Done)

Solution#2

public class Solution {
public int firstUniqChar(String s) {
if (s == null || s.length() == 0)
return -1;
if (s.length() == 1)
return 0;
int[] letters = new int[26];
for (int i = 0; i < 26; i++) {
letters[i] = 0;
}
char[] c = s.toCharArray();
int slow = 0, fast = 1;
letters[c[slow] - 'a'] = 1;
while (fast < c.length) {
while (c[fast] != c[slow]) {
letters[c[fast++] - 'a']++;
if (fast == c.length)
return slow;
}
letters[c[fast] - 'a']++;
while (++slow < c.length) {
if (letters[c[slow] - 'a'] <= 1) {
letters[c[slow] - 'a']++;
break;
}
}
if (fast < slow)
fast = slow + 1;
else
fast++;
}
return slow == c.length ? -1 : slow;
}
}

Solution#1

public class Solution {
public int firstUniqChar(String s) {
if (s == null || s.length() == 0)
return -1;
int[] position = new int[26];
for (int i = 0; i < 26; i++) {
position[i] = -1;
}
boolean[] notUnique = new boolean[26];
for (int i = 0; i < s.length(); i++) {
int index = s.charAt(i) - 'a';
if (position[index] == -1) {
position[index] = i;
} else {
notUnique[index] = true;
}
}
int min = -1;
for (int i = 0; i < 26; i++) {
if (!notUnique[i]) {
if (min == -1 || min > position[i] && position[i] != -1)
min = position[i];
}
}
return min;
}
}

Problem#2

*改用双指针法，并用数组代替hash表，效率大大增加(97.15%)

Problem#1

• 双指针法更快，需捋清思路

#### LeetCode387—First Unique Character in a String

2016-08-26 21:46:52

#### LeetCode之路：387. First Unique Character in a String

2017-06-02 16:11:16

#### 【python】【leetcode】【算法题目387—First Unique Character in a String】

2016-12-04 14:18:57

#### 387.leetcode First Unique Character in a String(easy)[统计字符串字符次数]

2016-08-22 19:51:53

#### 【LeetCode】387 First Unique Character in a String（java实现）

2016-10-20 00:37:41

#### First Unique Character in a String（字符串中的第一个唯一字符）

2016-09-22 11:18:17

#### 387. First Unique Character in a String Java

2016-09-04 18:37:49

#### leetcode_387. First Unique Character in a String 找第一个非重复的字符下标，python字典的应用

2016-10-16 16:34:28

#### 【两次过】Lintcode 209:First Unique Character in a String

2018-06-10 22:48:22

#### 387. First Unique Character

2017-09-29 14:47:50