刘子阳的博客

新车上路

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

  • 双指针法更快,需捋清思路
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014521967/article/details/53998786
个人分类: 算法练习
上一篇447. Number of Boomerangs#2(Done)
下一篇447. Number of Boomerangs
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭