首页 > 其他 > 详细

Valid Anagram

时间:2015-08-02 23:04:09      阅读:216      评论:0      收藏:0      [点我收藏+]

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.

 

Analyse: This question actually asks us to judge whether two strings have the same alphabats, i.e. they have same alphabats set and each alphabat has the occurence. 

1. judge equality after sorting.

    Runtime: 76ms.

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         return s == t;
7     }
8 };

 

2. Count the occurence of each alphabat and compare the occurence.

    Runtime: 12ms.

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

 

Valid Anagram

原文:http://www.cnblogs.com/amazingzoe/p/4696850.html

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