LEETCODE-Valid Anagram

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.
思路:统计各字符串中字母出现的次数;然后比较次数;

#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#define MAXN 300+10
using namespace std;
bool isAnagram(string s, string t) {
     int slength = s.size();
     int tlength = t.size();
     int k = 0;
     int A[26] = {0};
     int B[26] = {0};
     if( slength != tlength)
        return 0;
     else{
        for(int i = 0; i < slength; i++)
            A[s[i] - 'a']++;
        for(int j = 0; j < tlength; j++)
            B[t[j] - 'a']++;
        for(int i = 0; i < 26; i++){
            if( A[i] == B[i])
               k++;
        }
        if( k == 26)
            return 1;
        else
            return 0;
     }
}
int main()
{
    string s, t;
    bool a;
    cin >> s;
    cin >> t;
    a = isAnagram(s, t);
    cout << a;
    cout << endl;
}

https://leetcode.com/submissions/detail/38612737/
*另外
下面这串代码
思路为:用string s中的字母逐一在string t中寻找相同的字母,找到后将其从string t中剔除,判断最后t中是否剩余的字母,决定string s 与 string t是否相等;
在submit solution时出现time limit exceeded;
还不能解决问题!!

#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#define MAXN 300+10
using namespace std;
bool isAnagram(string s, string t) {
     int slength = s.size();
     int tlength = t.size();
     int L = tlength;
     for(int i = 0; i < slength; i++)
     {
         for(int j = 0; j < tlength; j++)
            {
                if( s[i] == t[j])
                {
                    for(int x = j; j < L-1; j++)
                    {
                        t[j] = t[j+1];
                    }
                    t[L-1] = '0';
                    L--;
                    break;
                }
            }
     }
     if(L == 0 && slength == tlength)
        return 1;
     else
        return 0;
}
int main()
{
    string s, t;
    bool a;
    cin >> s;
    cin >> t;
    a = isAnagram(s, t);
    cout << a;
    cout << endl;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值