LeetCode 242. 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.

翻譯

給兩個字串s與t,回傳t是否為s的重組字

範例:
s = "anagram", t = "nagaram" 回傳true
s = "rat", t = "car" 回傳false

思路

要比較兩個字串裡面的字元是否相同,首先可以判斷長度是否相等,不相等就可以直接判定為false, 接下來將重新排序後的字串比較是否相等。

解題

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isAnagram = function(s, t) {
    if(s.length != t.length) return false;

    var s = s.split("").sort().join("");
    var t = t.split("").sort().join("");

    return s == t;
};

results matching ""

    No results matching ""