LeetCode知识点总结 - 242

LeetCode 242. Valid Anagram

考点 难度
Hash Table Easy
题目

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

思路

用一个array存储s里面每个字母出现的次数,再减去t里面每个字母出现的次数。如果存在不为零则返回false

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

猜你喜欢

转载自blog.csdn.net/m0_59773145/article/details/120142234
242
今日推荐