MDGSF Software Engineer

[算法学习][leetcode] 242 Valid Anagram

2017-09-05
mdgsf
Art

https://leetcode.com/problems/valid-anagram/description/

题目

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.

Follow up:

What if the inputs contain unicode characters? How would you adapt your solution to such case?

题目翻译

题目解析

参考答案

#include <iostream>
#include <string>
#include <set>
using namespace std;

class Solution {
public:
    bool isAnagram(string s, string t)
    {
        if (s.size() != t.size())
        {
            return false;
        }

        int aiANSI[128] = { 0 };
        for (int i = 0; i < s.size(); i++)
        {
            aiANSI[s[i]]++;
        }

        for (int i = 0; i < t.size(); i++)
        {
            if (aiANSI[t[i]] <= 0)
            {
                return false;
            }
            else
            {
                aiANSI[t[i]]--;
            }
        }

        return true;
    }
};

int main()
{
    Solution o;
    bool bRet = o.isAnagram("ab", "a");
    return 0;
}

weixingongzhonghao

Similar Posts

Comments