Java O(n) Solution with comments


  • 0
    W
    // 思路: 哈希表
    public boolean canConstruct(String ransomNote, String magazine) {
    	int[] table = new int[26]; // only lowercase letters
    	for (char c : magazine.toCharArray()) { // 字符计数
    		table[c - 'a']++;
    	}
    	for (char c : ransomNote.toCharArray()) { // 递减字符计数
    		table[c - 'a']--;
    		if (table[c - 'a'] < 0) { // 字符短缺
    			return false;
    		}
    	}
    	return true;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.