首页 > 其他 > 详细

leetcode 242. Valid Anagram

时间:2019-10-08 22:53:09      阅读:100      评论:0      收藏:0      [点我收藏+]

Given two strings s and , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: 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的一个随机重排字符组成的字符串。

 

思路一:将s和t排序,排好序后,每个位置判断是否相同

思路二:只有小写字母,可以用大小为26的数组统计个数。(如果不止小写字母,可以用map)

 1 class Solution {
 2 public:
 3     bool isAnagram(string s, string t) {
 4         if (s.length() != t.length())
 5             return false;
 6         int cnt[26] = {0};
 7         for (int i = 0; i < s.length(); ++i) {
 8             cnt[s[i] - a]++;
 9             cnt[t[i] - a]--;
10         }
11         for (int i = 0; i < 26; ++i) {
12             if (cnt[i] != 0)
13                 return false;
14         }
15         return true;
16     }
17 };

 

leetcode 242. Valid Anagram

原文:https://www.cnblogs.com/qinduanyinghua/p/11638249.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!