Valid Anagarm
Problem:
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
You may assume the string contains only lowercase alphabets.
Analysis:
Use int[26] to store the word. First round add, second round minus. Then check if there is 0 in int[26].
Solution:
class Solution { public boolean isAnagram(String s, String t) { int[] map = new int[26]; for (char c: s.toCharArray()) { map[c - 'a']++; } for (char c: t.toCharArray()) { map[c - 'a']--; } for (int n: map) { if (n != 0) return false; } return true; } }
评论
发表评论