Sunday, June 28, 2015

Two Strings Are Anagrams Show result

Write a method anagram(s,t) to decide if two strings are anagrams or not.
Have you met this question in a real interview?
Yes
Example
Given s="abcd"t="dcab", return true.
Challenge
O(n) time, O(1) extra space
Tags Expand  

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