java 来自https://leetcode.com/problems/first-unique-character-in-a-string/discuss/

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 来自https://leetcode.com/problems/first-unique-character-in-a-string/discuss/相关的知识,希望对你有一定的参考价值。

// Solution 1
/// two traversals -- 29ms     O(n)

public class Solution {
    public int firstUniqChar(String s) {
        int freq [] = new int[26];
        for(int i = 0; i < s.length(); i ++)
            freq [s.charAt(i) - 'a'] ++;
        for(int i = 0; i < s.length(); i ++)
            if(freq [s.charAt(i) - 'a'] == 1)
                return i;
        return -1;
    }
}


// Solution 2
/// slow and fast pointers -- 18ms   O(n)
public int firstUniqChar(String s) {
            if (s==null || s.length()==0) return -1;
            int len = s.length();
            if (len==1) return 0;
            char[] cc = s.toCharArray();
            int slow =0, fast=1;
            int[] count = new int[128];
            count[cc[slow]]++;

            while (fast < len) {
                count[cc[fast]]++;
                // if slow pointer is not a unique character anymore, move to the next unique one
                while (slow < len && count[cc[slow]] > 1)
                    slow++;
                if (slow >= len)
                    return -1; // no unique character exist
                if (count[cc[slow]]==0) { // not yet visited by the fast pointer
                    count[cc[slow]]++;
                    fast=slow; // reset the fast pointer
                }
                fast++;
            }
            return slow;
        }

以上是关于java 来自https://leetcode.com/problems/first-unique-character-in-a-string/discuss/的主要内容,如果未能解决你的问题,请参考以下文章

20-05-01

两数之和(LeetCode)

leetcode刷题两数之和

算法leetcode|剑指 Offer 27. 二叉树的镜像|226. 翻转二叉树(rust很强)

算法leetcode|剑指 Offer 27. 二叉树的镜像|226. 翻转二叉树(rust很强)

算法leetcode|剑指 Offer 27. 二叉树的镜像|226. 翻转二叉树(rust很强)