Programming

Leetcode-242. Valid Anagram

Leetcode-242. Valid Anagram

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

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

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

Example 2:

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

判斷s、t字串,排序之後是否相等

<解法>

1. 用陣列比較


import java.util.Arrays;

class Solution {
    public boolean isAnagram(String s, String t) {
        char[] sArr = s.toCharArray();
        char[] tArr = t.toCharArray();

        Arrays.sort(sArr);
        Arrays.sort(tArr);

        return Arrays.equals(sArr,tArr);
    }
}

2. 使用一個長度為 26 的陣列來統計字母出現的次數(改善空間複雜度)


class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        
        int[] count = new int[26]; // 使用一個長度為 26 的陣列來統計字母出現的次數
        
        // 將 s 字串中的字母計數加 1
        for (char c : s.toCharArray()) {
            count[c - 'a']++;
        }
        
        // 將 t 字串中的字母計數減 1
        for (char c : t.toCharArray()) {
            count[c - 'a']--;
        }
        
        // 檢查每個字母計數是否為 0,如果有非 0 的計數則表示兩個字串不是異位詞
        for (int i = 0; i < 26; i++) {
            if (count[i] != 0) {
                return false;
            }
        }
        
        return true;
    }
}

<補充>.toCharArray() 把字串轉成字元


public class Main {
    public static void main(String args[]) {
        String Str = new String("Hello word");

        System.out.print("返回值 :" );
        System.out.println( Str.toCharArray() );
    }
}

將字符數組轉換為字符串

char[] charArray = {'H', 'e', 'l', 'l', 'o'};
String str = new String(charArray); // 将字符数组转换为字符串
System.out.println(str); // 输出 "Hello"