Leet Code OJ 242. Valid Anagram [Difficulty: Easy]

题目:
Given two strings s and t, write a function to determine if t 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.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

分析:
题意是给定2个字符串,判断这2个字符串是否由相同的字符组成,并且对应字符的个数一致。

代码实现(时间复杂度O(n^2)):

public class Solution {
    public boolean isAnagram(String s, String t) {
        char[] sarr=s.toCharArray();
        char[] tarr=t.toCharArray();
        if(sarr.length!=tarr.length){
            return false;
        }
        for(int i=0;i<sarr.length;i++){
            boolean found=false;
            for(int j=i;j<sarr.length;j++){
                if(sarr[i]==tarr[j]){
                    found=true;
                    if(i!=j){
                        tarr[j]=tarr[i];
                        tarr[i]=sarr[i];
                    }
                    break;
                }
            }
            if(found==false){
                return false;
            }
        }
        return true;
    }
}

你可能感兴趣的:(算法)