【LeetCode】242. Valid Anagram

Difficulty:easy

 More:【目錄】LeetCode Java實現html

Description

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

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

Example 1:ui

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

Example 2:spa

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

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

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

Intuition

use int[26] or HashMapblog

 

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)
ip

Space complexity : O(1)leetcode

 

 More:【目錄】LeetCode Java實現

相關文章
相關標籤/搜索