Leetcode Valid Anagram

本文介绍了一种使用C++编程语言来判断两个字符串是否互为异位词的方法。通过两种不同的实现方式,一种利用map存储字符频次进行比较,另一种采用vector优化存储,实现了高效的异位词判断。

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.

 

 1 #include<map>
 2 #include<string>
 3 #include<iterator>
 4 using namespace std;
 5 
 6 class Solution {
 7 public:
 8     bool isAnagram(string s, string t) {
 9         string temp1,temp2,temp3;
10         int c1,c2;
11         map<string,int> dictionary1,dictionary2;
12         for(int i=0;i<s.length();i++) {
13             temp1=s[i];
14             ++dictionary1[temp1];}
15         for(int j=0;j<t.length();j++) {
16             temp2=t[j];
17             ++dictionary2[temp2];}
18             
19         if(dictionary1.size()!=dictionary2.size()) return false;
20         for(auto i=dictionary1.begin();i!=dictionary1.end();i++)
21         {
22             c1=(*i).second;
23             temp3=(*i).first;
24             c2=dictionary2[temp3];
25             if(c1!=c2) return false;
26         }
27         return true;    
28         
29     }
30 };

 看到一个更好的方法:(别人的)

class Solution {
public:
    bool isAnagram(string s, string t) {
        vector<int> count(26, 0);  //全部初始化为0
        for(int i = 0; i < s.size(); i ++)
            count[s[i]-'a'] ++;      //把a,b,c转换成下标了- - 不是什么二维,二维应该是vector<vector<int >>
        for(int i = 0; i < t.size(); i ++)
            count[t[i]-'a'] --;
        for(int i = 0; i < 26; i ++)
            if(count[i] != 0)
                return false;
        return true;
    }
};

 


 

 tips:

 string当然不一定要初始化。

 C++中没有直接判断map是否相等的函数;

 map中有iterator;

 map中的元素是pair,我们可以用first来取关键字,second来取值;

转载于:https://www.cnblogs.com/LUO77/p/4959663.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值