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
Idea of solving the problem
When we do this, we should consider using the sort function.Because we can use sorting algorithms to sort arrays in order.If they are the same, that means they can be rearranged, and if they are different, that means they can’t be rearranged.So let’s simplify the problem to how to convert a string into an array.We can cut the string by pressing “” through the split method and store it in the array.Then we just have to compare the two to see if they are the same. The time complexity is O(1), and the space complexity is O(1). The time consumption is 2Mb.
Code
package main
import (
"fmt"
"reflect"
"sort"
"strings"
)
func main(){
s1 := "abc"
s2 := "cba"
fmt.Println(CheckPermutation(s1,s2))
}
func CheckPermutation(s1 string, s2 string) bool {
arr1:=strings.Split(s1,"")
arr2:=strings.Split(s2,"")
sort.Strings(arr1)
sort.Strings(arr2)
return reflect.DeepEqual(arr1, arr2)
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/check-permutation-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。