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

Valid Anagram

时间:2015-08-02 23:06:00      阅读:208      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!