158. Two strings are anagrams

158. Two strings are anagrams
 

Write a function anagram(s, t) to determine whether two strings can be changed into the same string by changing the order of letters.
Sample

Example 1:

Input: s = "ab", t = "ab"
Output: true

Example 2:

Input: s = "abcd", t = "dcba"
Output: true

Example 3:

Input: s = "ac", t = "ab"
Output: false

challenge

O(n) time complexity, O(1) extra space
Description

What is Anagram?

    Two strings can be the same after changing the character order

bool anagram(string &s, string &t) {
        // write your code here
        
        if(s.size() != t.size())
            return false;
            
        sort(s.begin(),s.end());
        sort(t.begin(),t.end());
        
        for(int i=0;i<s.size();i++)
        {
            if(s[i] != t[i])
            {
              return false;
           }
        }
        return true;
    }

Guess you like

Origin blog.csdn.net/yinhua405/article/details/111149238