11/2 morning

387. First Unique Character in a String

Each character and map it to establish the number of occurrences with a freq table, and then sequentially traverse the string to find the first occurrence of the character number 1, to return to its position, see the following code:

note

FREQ 1. [s.charAt (I) - 'A']. 1 == 
2. FREQ 256 covered with an array of all the characters
class Solution {
    public int firstUniqChar(String s) {
        int[] freq = new int[256];
        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;
    }
}

383. Ransom Note

Similarly, the number of characters in each magazine in a corresponding position on the index table with the record freq.

Traversing the second pass in this form ransomNote, if the value of the position corresponding to less than 0, then satisfied.

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        int[] freq = new int[26];
        for( int i = 0; i < magazine.length(); i++){
            freq[magazine.charAt(i) - 'a']++;
        }
        for( int i = 0; i < ransomNote.length(); i++){
            if( --freq[ransomNote.charAt(i) - 'a'] < 0 )
                return false;
        }
        return true;
    }
}

 

Guess you like

Origin www.cnblogs.com/Afei-1123/p/11781255.html