码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 242 Valid Anagram

时间:2016-10-29 07:46:07      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:term   class   val   problem   cti   and   hash   bsp   rmi   

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中的字母是否有相同出现频率。

 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 };

 

LeetCode 242 Valid Anagram

标签:term   class   val   problem   cti   and   hash   bsp   rmi   

原文地址:http://www.cnblogs.com/VickyWang/p/6009864.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!