[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的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,776评论 0 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,778评论 18 399
  • http://python.jobbole.com/85231/ 关于专业技能写完项目接着写写一名3年工作经验的J...
    燕京博士阅读 7,630评论 1 118
  • 老K旅途
    汇而阅读 153评论 0 0