本文介绍: 解题思想:直接遍历即可

力扣题-11.29

[力扣刷题攻略] Re:从零开始的力扣刷题生活

力扣题1:032. 有效的字母异位

解题思想:直接遍历即可

在这里插入图片描述

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if s==t:
            return False
        if len(s)!=len(t):
            return False
        char_count = {}
        for i in range(len(s)):
            if s[i] in char_count:
                char_count[s[i]] += 1
            else:
                char_count[s[i]] = 1
        for i in range(len(t)):
            if t[i] in char_count:
                char_count[t[i]] -=1
                if char_count[t[i]]<0:
                    return False
            else:
                return False
        return True
class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s == t) {
            return false;
        }
        if (s.length() != t.length()) {
            return false;
        }
        std::unordered_map<char, int> char_count;
        for (int i = 0; i < s.length(); ++i) {
            if (char_count.find(s[i]) != char_count.end()) {
                char_count[s[i]] += 1;
            } else {
                char_count[s[i]] = 1;
            }
        }
        for (int i = 0; i < t.length(); ++i) {
            if (char_count.find(t[i]) != char_count.end()) {
                char_count[t[i]] -= 1;
                if (char_count[t[i]] < 0) {
                    return false;
                }
            } else {
                return false;
            }
        }
        return true;
    }
};

原文地址:https://blog.csdn.net/yumeng3866/article/details/134690447

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_21916.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注