Leetcode interview question 01.02. Determine whether each other is a character rearrangement

CSDN Topic Challenge Phase 2
Participation Topic: Algorithm Solution


insert image description here

Topic link and description

https://leetcode.cn/problems/check-permutation-lcci/

Keywords: sort hash table

To judge whether they are character rearrangements, the length must be equal, and the same characters are equal;
based on these two conditions, you can use:

  • After sorting. compare strings
  • Record the comparison of the number of corresponding characters (the official solution is a bit oriented to the answer, the characters are not necessarily letters, so the hash table should be used)

Method 1: hash table

run screenshot

insert image description here

the code


    public boolean CheckPermutation(String s1, String s2) {
    
    
		if (s1.length() != s2.length()) {
    
    
			return false;
		}
		Map<Character, Integer> table = new HashMap<>();
		for (int i = 0; i < s1.length(); i++) {
    
    
			table.put(s1.charAt(i), table.getOrDefault(s1.charAt(i), 0) + 1);
		}
		for (int i = 0; i < s2.length(); i++) {
    
    
			table.put(s2.charAt(i), table.getOrDefault(s2.charAt(i), 0) - 1);
			if (table.getOrDefault(s2.charAt(i), 0) < 0) {
    
    
				return false;
			}
		}
		return true;
	 
    }

Method 2: Reorder

run screenshot

insert image description here

the code


    public boolean CheckPermutation(String s1, String s2) {
    
    
        if (s1.length() != s2.length()) {
    
    
            return false;
        }
        char[] str1 = s1.toCharArray();
        char[] str2 = s2.toCharArray();
        Arrays.sort(str1);
        Arrays.sort(str2);
        return Arrays.equals(str1, str2);
    }
 

end

Welcome to communicate in the comment area, check in every day, and rush! ! !

Guess you like

Origin blog.csdn.net/qq_35530042/article/details/127064670