判断字符串是否互为字符重排

  • Post author:
  • Post category:其他


 //方法一:
        Boolean bo = true;
        String s1 = "absc", s2 = "bcda";
        System.out.println(new Date()+"===========开始111========="+System.currentTimeMillis());
        if(s1.length() != s1.length()){
            bo = false;
        }
        char[] chars = s2.toCharArray();
        List<String> list = new ArrayList<>();
        for (int i = 0; i < s2.toCharArray().length; i++) {
            list.add(s2.toCharArray()[i]+"");
        }


        for (int i = 0; i < s1.toCharArray().length; i++) {
            if(!list.contains(s1.toCharArray()[i]+"")){
                bo = false;
            }
        }
        System.out.println(bo);
        System.out.println(new Date()+"===========结束22222========="+System.currentTimeMillis());
        //方法二:
        System.out.println(new Date()+"===========开始========="+System.currentTimeMillis());
        // 将字符串转换成字符数组
        char[] s1Chars = s1.toCharArray();
        char[] s2Chars = s2.toCharArray();
        // 对字符数组进行排序
        Arrays.sort(s1Chars);
        Arrays.sort(s2Chars);
        // 再将字符数组转换成字符串,比较是否相等



        System.out.println(new String(s1Chars).equals(new String(s2Chars)));
        System.out.println(new Date()+"===========结束========="+System.currentTimeMillis());


```由运行结果可以看出虽然两种方式速度都挺快但是第二种方式还是快了一点
![在这里插入图片描述](https://img-blog.csdnimg.cn/4c8a35cddb9243a98fdbc63777187f09.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5LmU5bCP5a6J5ZGQ,size_20,color_FFFFFF,t_70,g_se,x_16)




版权声明:本文为ZXCVBNM0_123456789原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。