LeetCode 题解(183): Valid Anagram

题目:

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.

题解:

sort或hashtable。

C++版:

class Solution {
public:
    bool isAnagram(string s, string t) {
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        return s == t;
    }
};

Java版:

public class Solution {
    public boolean isAnagram(String s, String t) {
        char[] sc = s.toCharArray();
        char[] tc = t.toCharArray();
        Arrays.sort(sc);
        Arrays.sort(tc);
        String sn = String.valueOf(sc);
        String tn = String.valueOf(tc);
        return sn.equals(tn);
    }
}

Python版:

class Solution:
    # @param {string} s
    # @param {string} t
    # @return {boolean}
    def isAnagram(self, s, t):
        if sorted(s) == sorted(t):
            return True
        return False

你可能感兴趣的:(Algorithm,LeetCode,面试题)