leetcode_1 Valid Anagram(sort)

  • 题目描述:

    Given two strings s and , write a function to determine if t is an anagram of s.

    Example 1:

    Input:s = "anagram", t = "nagaram"
    Output: true
    

    Example 2:

    Input:s = "rat", t = "car"
    Output: false
    

    Note:
    You may assume the string contains only lowercase alphabets. 意思:

判断t 是否为 s的变型词,即由相同的字母组成,但字母的顺序可能不同

  • 解题思路:通过建立映射的方法,因为字母只有26个所以建立一个26字母的map初始值为0在字符串中出现一次则加一,最后判断两个map是否相等
  • 解题代码 c++代码,利用一个vector 来实现映射
    class Solution {
    public:
        bool isAnagram(string s, string t) {
            if(s.size()!=t.size())
            {
                
                return false;
            }
            vector<int> map1(26,0),map2(26,0);
            for(int i=0;i<s.size();i++)
            {
                map1[s[i]-'a']+=1;
                map2[t[i]-'a']+=1;
            }
            return map1==map2;
    
            
        }
    };

    python3版本则使用一个字典来实现映射
    class Solution:
        def isAnagram(self, s: 'str', t: 'str') -> 'bool':
            if len(s)!=len(t):
                return False
            dict1,dict2={},{}
            for i in s:
                dict1[i]=dict1.get(i,0)+1
            for i in t:
                dict2[i]=dict2.get(i,0)+1
            return dict1==dict2
            
    
  • 题目总结:题目属于入门类题目,c++ 时间复杂度为o(n) 空间复杂度为o(n)

 

原文地址:https://www.cnblogs.com/zydxx/p/10420607.html