LeetCode 242 Valid Anagram

Problem:

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.

Summary:

给出字符串s和t,判断t是不是s的相同字母异序词。

Analysis:

1. Hash表,记录s中字母出现的次数,再判断t中的字母是否有相同出现频率。此方法也可以由map实现。

 1 class Solution {
 2 public:
 3     bool isAnagram(string s, string t) {
 4         int len1 = s.size(), len2 = t.size(), ch[26] = {0};
 5         
 6         for (int i = 0; i < len1; i++) {
 7             int tmp = s[i] - 'a';
 8             ch[tmp]++;
 9         }
10         
11         for (int i = 0; i < len2; i++) {
12             int tmp = t[i] - 'a';
13             ch[tmp]--;
14         }
15         
16         for (int i = 0; i < 26; i++) {
17             if (ch[i]) {
18                 return false;
19             }
20         }
21         
22         return true;
23     }
24 };

2. 分别给两字符串中字符由小到大排序,判断排序后两字符串是否相等即可。但这个方法效率较低。

1 class Solution {
2 public:
3     bool isAnagram(string s, string t) {
4         sort(s.begin(), s.end());
5         sort(t.begin(), t.end());
6         
7         return s == t ? true : false;
8     }
9 };

 

posted @ 2016-10-29 01:20  SillyVicky  阅读(197)  评论(0编辑  收藏  举报