LeetCode-242:Valid Anagram

来源:互联网 发布:淘宝卖大米 编辑:程序博客网 时间:2024/05/16 03:51

原题描述如下:

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

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

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


题意给定两个字符串,判断第二个字符串是否为第一个字符串打乱顺序的结果

解题思路:采用数组存储第一个串,值为该字符对应出现次数,然后遍历第二个串,将第一个串递减,若变为-1,则退出,返回false

Java代码:

public class Solution {
    public boolean isAnagram(String s, String t) {
        
        if(s.length() != t.length()){
            return false;
        }
        
        int[] array = new int[256];
        
        for(int i=0; i<s.length(); ++i){
            array[(int)s.charAt(i)] += 1;
        }
        
        for(int i=0; i<t.length(); ++i){
            array[(int)t.charAt(i)] -= 1;
            if(array[(int)t.charAt(i)] == -1){
                return false;
            }
        }
        
        return true;
    }
}
0 0