Wednesday, September 2, 2015

Leetcode: 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.
Understand the problem:
If two strings are anagram iff the sorted format is the same. 

Code (Java):
public class Solution {
    public boolean isAnagram(String s, String t) {
        if (s == null || s.length() == 0) {
            return t == null || t.length() == 0;
        }
        
        if (t == null || t.length() == 0) {
            return s == null || s.length() == 0;
        }
        
        if (s.length() != t.length()) {
            return false;
        }
        
        char[] sArr = s.toCharArray();
        char[] tArr = t.toCharArray();
        
        Arrays.sort(sArr);
        Arrays.sort(tArr);
        
        for (int i = 0; i < sArr.length; i++) {
            if (sArr[i] != tArr[i]) {
                return false;
            }
        }
        
        return true;
    }
}


1 comment:

  1. There is shocking news in the sports betting world.

    It has been said that every bettor must watch this,

    Watch this now or stop betting on sports...

    Sports Cash System - SPORTS CASINO ROBOT

    ReplyDelete