欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

判断是否为字符串重排(力扣)

程序员文章站 2024-02-21 14:10:10
...

判断是否为字符串重排(力扣)

 


import java.util.Arrays;

public class Test2 {
    public static void main(String[] args) {
        String s1 = "abc";
        String s2 = "cba";
        String s3 = "bcd";
        System.out.println(CheckPermutation(s1,s2));
        System.out.println(CheckPermutation2(s1,s3));
    }

    //字符串长度相等且互相包含
    public static boolean CheckPermutation(String s1, String s2) {
        if (s1.length() != s2.length()){
            return false;
        }
        for (int i = 0; i < s1.length(); i++) {
            if (!s2.contains(String.valueOf(s1.charAt(i)))){
                return false;
            }
        }
        for (int i = 0; i < s2.length(); i++) {
            if (!s1.contains(String.valueOf(s2.charAt(i)))){
                return false;
            }
        }
        return true;
    }

    //转字符数组排序再比较是否相等
    public static boolean CheckPermutation2(String s1, String s2) {
        char[] c1 = s1.toCharArray();
        Arrays.sort(c1);
        char[] c2 = s2.toCharArray();
        Arrays.sort(c2);
        return c1.equals(c2);
    }
}
相关标签: 每日一题