More:【目錄】LeetCode Java實現html
https://leetcode.com/problems/valid-anagram/java
Given two strings s and t , 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
use int[26] or HashMapblog
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; }
Time complexity : O(n)
ip
Space complexity : O(1)leetcode
More:【目錄】LeetCode Java實現