Solution of Check Permutation LCCI

本文介绍了一种判断两个字符串是否为彼此的置换的方法。通过将字符串转换为字符数组并进行排序,比较两个排序后的数组是否相等,以此来确定字符串是否可以通过重新排列字符变为另一个字符串。此方法的时间复杂度为O(n log n),空间复杂度为O(n)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值