LeetCode专题: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.

题目意思就是给你两个字符串s、t只包含小写字母,判断两个字符串中包含的字符是否相同。

解答
import java.util.Arrays;

/**
  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.
 */
public class ValidAnagram {

    public static boolean isAnagram(String s, String t) {

        //Basic judgment
        if (s.length() != t.length()) {
            return false;
        }

        //方法1 直接利用Arrays工具类帮我们排序和比较
//        char[] sc = s.toCharArray();
//        char[] tc = t.toCharArray();
        //对两个字符数组排序
//        Arrays.sort(sc);
//        Arrays.sort(tc);
        //判断两个排好序的字符数组是否一样
//        return  Arrays.equals(sc,tc);

        /**
         * 方法2:准备一个数组长度为26来存放s、t中所有字符,默认值为0,
         * s中的每个字符存入后找到相应的位置(该字符)加一,字符串t中的每个字符存入后减一,
         * 再遍历数组如果数组所有位置都为零则待变s,t中包含相同的字符。
         *
         * 准备的数组:
         * 值  :0 0 0 0 0 0 0 0 0 0
         * 索引:0 1 2 3 4 5 6 7 8 9
         *
         * a b c d e .... 想快速获取下标
         * 0 1 2 3 4 .... 每个字符对应的下标
         * 计算公式:'x'-'a' :任意字符减去a字符
         * 例如:s="net"  t="ten"
         *  n: index='n'-'a' e: index='e'-'a'
         */


        //准备一个数组分别存放给定字符串中的每个字符
        int [] count = new int[26];
        // a b c d e .... 想快速获取下标
        // 0 1 2 3 4 ....
        //'x'-'a' :任意字符减去a字符
        for (int i = 0;i < s.length();i++){
            //s字符串中的字母,计算对应的下标s.charAt(i) - 'a',放入数组中加一
            count[s.charAt(i) - 'a']++;
            //s字符串中的字母,计算对应的下标s.charAt(i) - 'a',放入数组中减一
            count[t.charAt(i) - 'a']--;
        }
        for (int i = 0;i < count.length;i++){
            if (count[i]!=0) return false;
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isAnagram("net", "ten"));
    }
}

猜你喜欢

转载自blog.csdn.net/yu0_zhang0/article/details/81675392