关闭

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

54人阅读 评论(0) 收藏 举报
分类:

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

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:5541次
    • 积分:1204
    • 等级:
    • 排名:千里之外
    • 原创:120篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条