1. 程式人生 > >LeetCode之有效的字母異位詞

LeetCode之有效的字母異位詞

有效的字母異位詞

給定兩個字串 st ,編寫一個函式來判斷 t 是否是 s 的一個字母異位詞。

示例 1:

輸入: s = "anagram", t = "nagaram"
輸出: true

示例 2:

輸入: s = "rat", t = "car"
輸出: false

說明:
你可以假設字串只包含小寫字母。

進階:
如果輸入字串包含 unicode 字元怎麼辦?你能否調整你的解法來應對這種情況?

方法一:

這個會超時,扎心!

public boolean isAnagram(String s, String t) {
    if
(s.length() != t.length()) return false; for(char str: s.toCharArray();) { System.out.println(str); int a = (int) s.chars().filter(c -> c == str).count(); int b = (int) t.chars().filter(c -> c == str).count(); if(a != b) return false; }
return true; }

方法二:

這個使用先用排序將字元排好,然後在進行字串比較。

public boolean isAnagram(String s, String t) {
    if(s.length() != t.length())
        return false;
    char[] s_strs = s.toCharArray();
    char[] t_strs = t.toCharArray();
    Arrays.sort(s_strs);
    Arrays.sort(t_strs);
    String code_s =
new String(s_strs); String code_t = new String(t_strs); if(code_s.compareTo(code_t) == 0) { return true; } return false; }

方法三:

統計每個字元的個數,然後在比較。和方法一的思路一樣。

public boolean isAnagram(String s, String t) {
    if(s.length() != t.length())
        return false;
    int[] s_int = new int[26];
    int[] t_int = new int[26];
    for(char str:s.toCharArray()) {s_int[str-'a']++;}
    for(char str:t.toCharArray()) {t_int[str-'a']++;}
    for(int i = 0; i < 26; i++) {
        if(s_int[i] != t_int[i])
            return false;
    }
    return true;
}