Given two strings,write a method to decide if one is a permutation of the other.
Example 1:
Input: s1 = "abc", s2 = "bca"
Output: true
Example 2:
Input: s1 = "abc", s2 = "bad"
Output: false
Note:
0 <= len(s1) <= 100
0 <= len(s2) <= 100
Solutions
Solution 1: Array or Hash Table
Thinking
Two strings are permutations of each other iff they have the same character multiset. Unequal lengths can be rejected immediately; enumerating permutations of \(s_1\) is far more expensive than the input size requires.
The bottleneck is verifying frequencies in linear time. Count characters in \(s_1\), then decrement while scanning \(s_2\): a negative count means the frequencies differ.
The tests use only lowercase letters, so an array of length \(26\) serves as the table. Comparing lengths first avoids counting on inputs that cannot match.
First, we check whether the lengths of the two strings are equal. If they are not equal, we directly return false.
Then, we use an array or hash table to count the occurrence of each character in string \(s1\).
Next, we traverse the other string \(s2\). For each character we encounter, we decrement its corresponding count. If the count after decrementing is less than \(0\), it means that the occurrence of characters in the two strings is different, so we directly return false.
Finally, after traversing string \(s2\), we return true.
Note: In this problem, all test case strings only contain lowercase letters, so we can directly create an array of length \(26\) for counting.
The time complexity is \(O(n)\), and the space complexity is \(O(C)\). Here, \(n\) is the length of the string, and \(C\) is the size of the character set. In this problem, \(C=26\).