【LeetCode】242. Valid Anagram

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实现

 

posted @ 2019-10-10 10:30  华仔要长胖  阅读(239)  评论(0编辑  收藏  举报