Valid Anagram from LeetCode

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

For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.數組

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


題目比較直觀,只須要檢查兩個字符串中,相同字符是否出現了一樣的次數,而且沒有多餘的字符,便可;code

public class Solution {
    public boolean isAnagram(String s, String t) {
        int[] map = new int[26];

        char[] cs = s.toCharArray();

        for(char c : cs) {
            int x = c - 'a';
            map[x] += 1;
        }

        cs = t.toCharArray();

        for(char c : cs) {
            int x = c - 'a';
            if(map[x] == 0) {
                return false;
            }
            map[x] -= 1;
        }

        for(int x : map) {
            if(x != 0) {
                return false;
            }
        }
        return true;
    }
}
  1. 利用題目中只會出現小寫字母,能夠使用一個26位的int數組,分別表示a~z的出現的次數;orm

  2. 先計算s中字符出現的次數,字符串

  3. 而後遍歷t,並減小該字符出現的次數;若是遇到某個字符,其出現次數已經被減到了0,那麼該字符是在t中多出現了一次,返回false便可;string

  4. 遍歷完t,再檢查一遍是否有字符的出現次數沒有被減到0的狀況;若是存在,說明該字符在s中出現的次數比在t中多;返回false;it

  5. 最後返回true便可;io

  6. 時間複雜度爲o(n), 空間複雜度爲常量;
    function

相關文章
相關標籤/搜索