文章 224
评论 6
浏览 200766
String - 242. Valid Anagram

String - 242. Valid Anagram

242. Valid Anagram

Given two strings s and _t _, write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

思路:

记录第一个数组每个元素出现的次数,然后去对比另一个数组。

代码:

java:

class Solution {

    /*public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) return false;
        
        int[] m1 = new int[128];
        int[] m2 = new int[128];
        char[] ss = s.toCharArray();
        char[] ts = t.toCharArray();
        
        for (int i = 0; i < ss.length; i++) {
            m1[ss[i]] += 1;
            m2[ts[i]] += 1;
        }
        
        for (int i = 0; i < 128; i++){
            if(m1[i] != m2[i]) return false;
        }
        
        return true;
    }*/
    
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) return false;
        
        int[] m = new int[128];
        char[] ss = s.toCharArray();
        char[] ts = t.toCharArray();
        
        for (int i = 0; i < ss.length; i++) {
            m[ss[i]]++;
            }
        
        for (int i = 0; i < ts.length; i++){
            m[ts[i]]--;
            if (m[ts[i]] < 0) return false;
        }
        
        return true;
    }
}

标题:String - 242. Valid Anagram
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/06/29/1561816552055.html

Nothing just happens, it's all part of a plan.

取消