LeetCode - Easy - 242. Valid Anagram

Topic

  • Sort
  • Hash Table

Description

https://leetcode.com/problems/valid-anagram/

Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: 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?

Analysis

Submission

public class ValidAnagram {
	
	public boolean isAnagram1(String s, String t) {
		if (s == null || t == null || s.length() != t.length())
			return false;

		int[] array = new int[26];

		for (int i = 0; i < s.length(); i++) {
			array[s.charAt(i) - 'a']++;
		}

		for (int i = 0; i < t.length(); i++) {
			array[t.charAt(i) - 'a']--;
		}

		for (int elem : array) {
			if (elem != 0)
				return false;
		}

		return true;
	}

	public boolean isAnagram2(String s, String t) {
		char[] sChar = s.toCharArray();
		char[] tChar = t.toCharArray();

		Arrays.sort(sChar);
		Arrays.sort(tChar);

		return Arrays.equals(sChar, tChar);
	}

}

Test

import static org.junit.Assert.*;
import org.junit.Test;

public class ValidAnagramTest {

	@Test
	public void test1() {
		ValidAnagram obj = new ValidAnagram();

		assertTrue(obj.isAnagram1("anagram", "nagaram"));
		assertTrue(obj.isAnagram1("", ""));
		assertFalse(obj.isAnagram1("rat", "car"));
	}
	
	@Test
	public void test2() {
		ValidAnagram obj = new ValidAnagram();
		
		assertTrue(obj.isAnagram2("anagram", "nagaram"));
		assertTrue(obj.isAnagram2("", ""));
		
		assertFalse(obj.isAnagram2("rat", "car"));
		assertFalse(obj.isAnagram2("aa", "bb"));
	}
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页