首页 > 学院 > 开发设计 > 正文

LeetCode242 Valid Anagram

2019-11-08 19:24:48
字体:
来源:转载
供稿:网友

题目

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。

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自动去重,可以参考我的上一篇博客.


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表