LeetCode#242 Valid Anagram (week5)

week5

题目

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.
原题地址:https://leetcode.com/problems/valid-anagram/description/

解析

题目大意是给两个字符串,判断它们是否一个字符串能否通过打乱顺序得到另一个字符串,是则返回true,反之返回false。注意到Note中提示可以考虑字符串中的字符仅为小写字母,因此字符串中的每个字符只有26种可能。
大致思路为用一个大小为26的int字符串,分别代表a-z,检索两个字符串的每个字符,对第一个字符串中出现的字符,对相应的数组+1,对于第二个字符串中出现的字符,相应数组-1,如果两个字符串仅仅顺序不同,则最终数组的每个元素均为0。

代码

class Solution {
public:
    bool isAnagram(string s, string t) {
        /*如果两个字符串长度不同则可以直接认定两个字符串存在除顺序之外的差别*/
        if (s.length() != t.length()) {
            return false;
        }
        int *counter = new int[26];
        for (int i = 0; i < 26; ++i) {
            counter[i] = 0;
        }
        for (int i = 0; i < s.length(); ++i) {
            int pos1 = (int)(s[i] - 'a');
            counter[pos1]++;
            int pos2 = (int)(t[i] - 'a');
            counter[pos2]--;
        }
        for (int i = 0; i < 26; ++i) {
            if (counter[i] != 0) {
                return false;
            }
        }
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值