Write a method
Have you met this question in a real interview?anagram(s,t)
to decide if two strings are anagrams or not.
Yes
Example
Given
s="abcd"
, t="dcab"
, return true
.
Challenge
Tags Expand
O(n) time, O(1) extra space
public class Solution {
/**
* @param s: The first string
* @param b: The second string
* @return true or false
*/
public boolean anagram(String s, String t) {
// write your code here
if(s.length() != t.length()) return false;
int[] record = new int[256];
for(int i = 0; i < s.length(); i++){
record[(int)s.charAt(i)]++;
}
for(int i = 0; i < t.length(); i++){
record[(int)t.charAt(i)]--;
if(record[(int)t.charAt(i)] < 0) return false;
}
return true;
}
};
No comments:
Post a Comment