This is the 31st day of my participation in the August Text Challenge.More challenges in August

Valid letter heterotopic word

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

** Note: ** If each character in s and T occurs the same number of times, s and T are said to be alphabetic allographs.

Advanced: What if the input string contains Unicode characters? Can you adjust your solution to this situation?

Examples can be found on the LeetCode website.

Source: LeetCode link: leetcode-cn.com/problems/va… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Solution 1: string traversal
  • First, if the length of s and t are not equal, it means that s and T cannot be letter heterotopic words. Return false.
  • Otherwise, when the length of S and T is equal, a Map is first declared as count to record the number of characters in S and T, where key is the character and value is the number of characters. Then, characters in S and T are traversed. During the traversal, characters in S and T are incremented by one. If there is a non-0 value in the values of count, return false. Otherwise return true.

Advanced methods have not been considered for the time being, subsequent optimization.

import java.util.HashMap;
import java.util.Map;

public class LeetCode_242 {
    public static boolean isAnagram(String s, String t) {
        // If the length of s and t are not equal, it means that s and t cannot be letter heterotopic. Return false.
        if(s.length() ! = t.length()) {return false;
        }
        // This Map records the number of characters in s and t. Key is the number of characters, and value is the number of characters
        Map<Character, Integer> count = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            // the character in s, plus one
            if(count.get(s.charAt(i)) ! =null) {
                count.put(s.charAt(i), count.get(s.charAt(i)) + 1);
            } else {
                count.put(s.charAt(i), 1);
            }
            // the character in t, minus one
            if(count.get(t.charAt(i)) ! =null) {
                count.put(t.charAt(i), count.get(t.charAt(i)) - 1);
            } else {
                count.put(t.charAt(i), -1); }}for (Integer value : count.values()) {
            if(value ! =0) {
                return false; }}return true;
    }

    public static void main(String[] args) {
        System.out.println(isAnagram("anagram"."nagaram")); }}Copy the code

You have to be true to your own dream before you care if it shines.