Difficulty:easy

 More:【目录】LeetCode Java实现

Description

https://leetcode.com/problems/valid-anagram/

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.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

Intuition

use int[26] or HashMap

 

Solution

    public boolean isAnagram(String s, String t) {
        int[] freq = new int[26];
        for(int i=0; i<s.length(); i++)
            freq[s.charAt(i)-'a']++;
        for(int i=0; i<t.length(); i++)
            freq[t.charAt(i)-'a']--;
        for(int f : freq)
            if(f!=0)
                return false;
        return true;
    }

  

Complexity

Time complexity : O(n)

Space complexity : O(1)

 

 More:【目录】LeetCode Java实现

 

相关文章:

  • 2021-09-28
  • 2021-12-02
  • 2022-01-24
  • 2021-10-12
  • 2021-08-30
  • 2022-12-23
猜你喜欢
  • 2021-05-07
  • 2021-04-11
  • 2021-06-20
  • 2022-12-23
  • 2022-12-23
  • 2022-01-21
相关资源
相似解决方案