LeetCode242有效的字母异位词

100 阅读1分钟

🍀有效字母的异位词

描述:

 # 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
 ​
 注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。
 ​
  
 ​
 示例 1:
 ​
 输入: s = "anagram", t = "nagaram"
 输出: true
 示例 2:
 ​
 输入: s = "rat", t = "car"
 输出: false
  
 ​
 提示:
 ​
 1 <= s.length, t.length <= 5 * 104
 s 和 t 仅包含小写字母

思考:

实现:

这个题和之前的383题很类似,用数组进行一个数组的记录,每查到一个字符就++,然后用另外一个字符串中的字符做--,最后遍历记录数组,不为0返回false,都是0返回true。

 class Solution {
     public boolean isAnagram(String s, String t) {
 ​
         int[] arr = new int[26];
         int temp;
 ​
         for (int i = 0; i < s.length(); i++) {
             temp = s.charAt(i) - 'a';
             arr[temp]++;
         }
         for (int i = 0; i < t.length(); i++) {
             temp = t.charAt(i) - 'a';
             arr[temp]--;
         }
         for (int i = 0; i < arr.length; i++) {
             if (arr[i] != 0) {
                 return false;
             }
         }
 ​
         return true;
     }
 }

测试一下!

image.png

大佬的代码:

还有很多种方法。

 class Solution {
     public boolean isAnagram1(String s, String t) {
         char[] sChars = s.toCharArray();
         char[] tChars = t.toCharArray();
         Arrays.sort(sChars);
         Arrays.sort(tChars);
         return Arrays.equals(sChars, tChars);
     }
 ​
     public boolean isAnagram2(String s, String t) {
         Map<Character, Integer> map = new HashMap<>();
         for (char ch : s.toCharArray()) {
             map.put(ch, map.getOrDefault(ch, 0) + 1);
         }
         for (char ch : t.toCharArray()) {
             Integer count = map.get(ch);
             if (count == null) {
                 return false;
             } else if (count > 1) {
                 map.put(ch, count - 1);
             } else {
                 map.remove(ch);
             }
         }
         return map.isEmpty();
     }
 ​
     public boolean isAnagram3(String s, String t) {
         int[] sCounts = new int[26];
         int[] tCounts = new int[26];
         for (char ch : s.toCharArray()) {
             sCounts[ch - 'a']++;
         }
         for (char ch : t.toCharArray()) {
             tCounts[ch - 'a']++;
         }
         for (int i = 0; i < 26; i++) {
             if (sCounts[i] != tCounts[i]) {
                 return false;
             }
         }
         return true;
     }
 ​
     public boolean isAnagram4(String s, String t) {
         int[] counts = new int[26];
         t.chars().forEach(tc -> counts[tc - 'a']++);
         s.chars().forEach(cs -> counts[cs - 'a']--);
         return Arrays.stream(counts).allMatch(c -> c == 0);
     }
 ​
     public boolean isAnagram(String s, String t) {
         return Arrays.equals(s.chars().sorted().toArray(), t.chars().sorted().toArray());
     }
 }

\