[LeetCode By Go 47]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.

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

题目大意

判断字符串t是否为s打乱顺序后的结果。开始还以为判断是否是回文串。

anagram 英[ˈænəgræm] 美[ˈænəˌɡræm]
n.
由颠倒字母顺序而构成的字[短语];
[网络] 变位词; 颠倒顺序字; 字谜游戏;

解题思路

两个字符串都进行排序,判断每一位是否相同
先将string转换为[]rune,可以兼容Unicode
使用 sort.Sort(data Interface) 进行排序,需要实现sort.Interface

代码

type RuneSlice []rune

func (s RuneSlice) Len() int           { return len(s) }
func (s RuneSlice) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s RuneSlice) Less(i, j int) bool { return s[i] < s[j] }

func isAnagram(s string, t string) bool {
    s1 := []rune(s)
    t1 := []rune(t)

    len1 := len(s1)
    len2 := len(t1)

    if len1 != len2 {
        return false
    }

    sort.Sort(RuneSlice(s1))
    sort.Sort(RuneSlice(t1))
    for i := 0; i < len1; i++{
        if s1[i] != t1[i] {
            return false
        }
    }

    return true
}

你可能感兴趣的:([LeetCode By Go 47]242. Valid Anagram)