Letcode Valid Anagram 효율적인 해법

3876 단어 LeetCode
// Author : yqtao
// Date : 2016-6.19
// Email :[email protected]

/********************************************************************************** * * Given two strings s and t, write a function to determine if t is an anagram of s. *    t   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. * **********************************************************************************/
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
//        ,   
//         
bool isAnagranm(string &s, string &t)
{
    sort(s.begin(), s.end());
    sort(t.begin(), t.end());
    if (s == t)
        return true;
    else
        return false;
}
//     ,     
bool isAnagranm1(string &s, string &t)
{
    int map[26] = { 0 };
    for (int i = 0; i < s.size(); i++)
        map[s[i] - 'a']++;//      map    
    for (int i = 0; i < t.size(); i++)
        map[t[i] - 'a']--;
    for (int i = 0; i < sizeof(map) / sizeof(map[0]); i++)
        if (map[i] != 0)
            return false;
    return true;//  map    0,  true


}
int main()
{
    string s = "nagaram";
    string p = "nagaram";
    cout << boolalpha << isAnagranm(s, p) << endl;//80ms
    cout << boolalpha << isAnagranm1(s, p) << endl;//12ms
}

좋은 웹페이지 즐겨찾기