判断两个给定的字符串排序后是否⼀致

问题描述

给定两个字符串,请编写程序,确定其中⼀个字符串的字符重新排列后,能否变成另⼀个字符串。 这⾥规定【⼤⼩写为不同字符】,且考虑字符串重点空格。给定⼀个string s1和⼀个string s2,请返回⼀个bool, 代表两串是否重新排列后可相同。 保证两串的⻓度都⼩于等于5000。

解题思路

⾸先要保证字符串⻓度⼩于5000。之后只需要⼀次循环遍历s1中的字符在s2是否都存在即可。

golang方案

package program

import (
    "fmt"
    "strconv"
    "strings"
    "testing"
)

func Test_3(t *testing.T)  {
    s1 := "12345678900"
    s2 := "01234567890"
    fmt.Println(isSame(s1, s2))
}


func isSame(s1, s2 string) bool {
    s1r := []rune(s1)
    s2r := []rune(s2)
    if len(s1r) > 5000 || len(s2r) > 5000 || len(s2r) != len(s1r) {
        return false
    }
    for s := range s1r{
        if strings.Count(s1, strconv.Itoa(s)) != strings.Count(s2, strconv.Itoa(s)) {
            return false
        }
    }
    return true
}

Python方案

def is_same(s1, s2) -> bool:
    if len(s1) > 5000 or len(s2) > 5000 or len(s2) != len(s1):
        return False
    for s in s1:
        if s1.count(s) != s2.count(s):
            return False
    return True


s1 = "12345678900"
s2 = "012345678901"
print(is_same(s1, s2))

java方案

package com.zhf.algorithm;

import org.apache.commons.lang3.StringUtils;

public class Test1 {
    public static void main(String[] args) {
        String s1 = "12345678900";
        String s2 = "01234567890";
        System.out.println(isSame(s1, s2));
    }

    private static boolean isSame(String s1, String s2) {
        if (s1.length() > 5000 || s2.length() > 5000 || s1.length() != s2.length()) {
            return false;
        }
        for (char s : s1.toCharArray()) {
            if (StringUtils.countMatches(s1, s) != StringUtils.countMatches(s2, s)) {
                return false;
            }
        }
        return true;
    }


}

results matching ""

    No results matching ""