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

leetcode_Valid Anagram_easy

时间:2015-08-08 21:21:56      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c++   map   string   

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.

方法:使用两个map来保持对应的两个字符串的字符个数,对字符个数进行统计,然后遍历两个map看是否完全相同 。

class Solution {
public:
    bool isAnagram(string s, string t) {
        map<char,int> sMap,tMap;
        for(int i=0; i<s.length(); i++)
            sMap[s[i]]++;
        for(int i=0; i<t.length(); i++)
            tMap[t[i]]++;
        map<char,int>::iterator sIter,tIter;
        sIter=sMap.begin();
        tIter=tMap.begin();
        while(sIter!=sMap.end() && tIter!=tMap.end() && sIter->first==tIter->first && sIter->second==tIter->second)
        {
            sIter++;
            tIter++;
        }
        if(sIter==sMap.end() && tIter==tMap.end())
            return true;
        else
            return false;
    }
};



版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode_Valid Anagram_easy

标签:leetcode   c++   map   string   

原文地址:http://blog.csdn.net/u013861066/article/details/47362021

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