Leetcode242. Effective word ectopic word

Title Description

Given two strings s and t, t write a function to determine whether the ectopic letters of the word s.

Example 1:

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

Example 2:

Input: s = "rat", t = "car"
Output: false

Description:

You can assume that the string contains only lowercase letters.

answer

Understanding, mainly refers to a hash more correspondence relationship, not necessarily bound by a particular data structure. The main question uses hashing and sorting method.

Hash (java)

Idea: As all the possible space is not large, so consider using a hash table method, maintaining an array of all the letters of the location, the original array plus a case of a letter, a letter met the target array minus one. Finally, check whether the array elements are zero.

public boolean isAnagram(String s, String t) {
    if (s.length() != t.length()) {
        return false;
    }
    int[] counter = new int[26];
    for (int i = 0; i < s.length(); i++) {
        counter[s.charAt(i) - 'a']++;
        counter[t.charAt(i) - 'a']--;
    }
    for (int count : counter) {
        if (count != 0) {
            return false;
        }
    }
    return true;
}

Complexity Analysis

  • Time complexity: O (n)
  • Space complexity: O (1)

Sorting (java)

Thinking: two strings directly into the array is sorted, and then check the consistency or not.

public boolean isAnagram(String s, String t) {
    if (s.length() != t.length()) {
        return false;
    }
    char[] str1 = s.toCharArray();
    char[] str2 = t.toCharArray();
    Arrays.sort(str1);
    Arrays.sort(str2);
    return Arrays.equals(str1, str2);
}
  • Time complexity: O (n)
  • Space complexity: O (n)
Published 43 original articles · won praise 20 · views 1450

Guess you like

Origin blog.csdn.net/Chen_2018k/article/details/104787060