Sword refers to offer—50. The first character that appears only once—analysis and code (Java)

Sword refers to offer-50. The first character that appears only once-analysis and code [Java]

1. Title

Find the first character that appears only once in a string (0 <= string length <= 10000, all composed of letters), and return its position, if not, return -1 (case sensitive).

Two, analysis and code

1. Hash table

(1) Thinking

An intuitive idea of ​​this question is that in the process of traversing a string, it is judged whether the character has appeared and recorded within O(1) time complexity, so that the overall complexity is controlled at O(n).
This idea can be achieved in combination with a hash table, and there are 2 points that can be optimized:
1) The number of letters is limited, and can be directly converted into continuous numbers in combination with its ASCII code, so the hash table can be realized through an array Function;
2) If the number of characters that appear in the hash table is recorded, the position of the character needs to be traversed again, so the position of the character can be directly recorded and the repeated characters can be distinguished, for example, The position of the character that has appeared is recorded as -1, the position of the repeated occurrence is recorded as -2, and the position of the first occurrence is recorded, so that the required answer can be obtained during one traversal.

(2) Code

public class Solution {
    
    
    public int FirstNotRepeatingChar(String str) {
    
    
        if (str.length() == 0)
            return -1;
        int[] chars = new int[58];
        for (int i = 0; i < 58; i++)
            chars[i] = -1;
        
        int base = (int)'A';
        for (int i = 0; i < str.length(); i++) {
    
    
            int index = (int)str.charAt(i) - base;
            if (chars[index] == -1)
                chars[index] = i;
            else if (chars[index] > -1)
                chars[index] = -2;
        }
        
        int ans = -1;
        for (int i = 0; i < 58; i++)
            if (chars[i] > -1 && (ans == -1 || chars[i] < ans))
                ans = chars[i];
        
        return ans;
    }
}

(3) Results

Running time: 28ms, occupied memory: 9468k.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/109267007