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.
Note:
You may assume the string contains only lowercase alphabets.
public class Solution { public boolean isAnagram(String s, String t) { //因为是26个字母,因此可以借助size为26的数组进行计算,下标代表字母,值为个数 //注意遍历第二个string时,返回false的技巧!! int c[]=new int[26]; int lens=s.length(); int lent=t.length(); if(lens!=lent) return false; for(int i=0;i<lens;i++){ c[s.charAt(i)-‘a‘]++; } for(int j=0;j<lent;j++){ if(c[t.charAt(j)-‘a‘]==0)return false; c[t.charAt(j)-‘a‘]--; } return true; } }
时间: 2024-12-23 12:43:06