2015年11月4日星期三

Leetcode 242 Valid Anagram

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.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
Solution 1: easy count problem
 public class Solution {  
   public boolean isAnagram(String s, String t) {  
     int n=s.length();  
     if (n!=t.length()) return false;  
     int[] count=new int[256];  
     for (int i=0; i<n; i++) count[s.charAt(i)]++;  
     for (int i=0; i<n; i++) {  
       if (--count[t.charAt(i)]==-1) return false;  
     }  
     return true;  
   }  
 }  

没有评论:

发表评论