242. Valid Anagram

242. Valid Anagram

Description:
Given two strings s and t, write a function to determine if t is an anagram of s.
note:
You may assume the string contains only lowercase alphabets.
Example:
For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.
Link:
https://leetcode.com/problems/valid-anagram/
Analysis:
这道题至少有两种思路:
A. 分别统计字符串s和t中每个字母出现的频率,若相同,则认为两个字符串是由字母顺序颠倒构成的。
B. 在s和t长度相同的情况下,分别找出在字符串s中和t对应的每一个字母,如果每个字母都完全对应,则认为他们是由字母顺序颠倒构成的。
对应这两种思路共有两种方法,见源码。
Source Code(C++):

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

/********************************分别统计s和t中字母出现的频率到数组中,比较各个字母出现的频率从而得出结果***********************************************/
/*
class Solution {
public:
    bool isAnagram(string s, string t) {
        vector<int> s_alphabet(26, 0), t_alphabet(26, 0);
        for (int i=0; i<s.length(); i++) {
            s_alphabet.at(s.at(i)-97)++;
        }
        for (int i=0; i<t.length(); i++) {
            t_alphabet.at(t.at(i)-97)++;
        }
        for (int i=0; i<s_alphabet.size(); i++){
            if (s_alphabet.at(i) != t_alphabet.at(i)) {
                return false;
            }
        }
        return true;
    }
};
*/
/********************************直接将s中的每一个字母与t比对***********************************************/
class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.length() !=t.length()) {
            return false;
        }
        else {
            for (int i=0; i<s.length(); i++) {
                int ind = t.find(s.at(i));
                if (ind == string::npos) {
                    return false;
                }
                else {
                    t.erase(ind, 1);
                }
            }
            return true;
        }
    }
};

int main() {
    Solution sol;
    cout << sol.isAnagram("anagram", "nagaram");
    cout << sol.isAnagram("rat", "car");
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值