前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode242 Valid Anagram

LeetCode242 Valid Anagram

作者头像
用户1665735
发布2019-02-19 14:29:19
4050
发布2019-02-19 14:29:19
举报
文章被收录于专栏:kevindroidkevindroid

题目

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.

解法

和387题类似,都可以使用统计每个字符出现的个数的方式来比较,只要所有字符出现的次数相同且两个字符串不行等,则返回true。需要注意的是,根据leetcode的评价标准,两个空串返回true。

代码语言:javascript
复制
public boolean isAnagram(String s, String t) {
        int lenS = s.length();
        int lenT = t.length();
        if (lenS == 0 && lenT == 0) return true;
        if (lenS == 1 && lenT == 1 && s.equals(t)) return true;
        if (lenS != lenT) return false;
        if (s.equals(t)) return false;
        int[] recordS = new int[26];
        int[] recordT = new int[26];
        for (int i = 0; i < lenS; i++) {
            char c1 = s.charAt(i);
            char c2 = t.charAt(i);
            int index1 = c1 - 'a';
            int index2 = c2 - 'a';
            recordS[index1]++;
            recordT[index2]++;
        }

        for (int i = 0; i < 26; i++)
            if (recordS[i] != recordT[i])
                return false;

        return true;
    }

扩展

如果需要加入unicode字符,那么上一种方式就不可行,因为小写字母只有26个,但unicode字符有6万多个,使用数组来一一对应开销过大。这时就可以使用hashmap来存储键值对,因为hashmap自动去重,可以参考我的上一篇博客.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年02月16日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 解法
  • 扩展
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档