首页 > 其他 > 详细

string_Q2

时间:2021-04-24 10:15:10      阅读:15      评论:0      收藏:0      [点我收藏+]
package chapter1;
/*
 * Q:given two string,check one of them can be got by another permutation again
 * E:"abcdb","dcbab"->true
 * S1:check the char and it‘s nums of two strings are same
 * create two array which index maps value of char
 * count the char‘s num
 * check the char and num are same
 * S2:sort two string,compare them are equal
 */
public class Q2 {
    public static boolean CheckPermutation1(String s1,String s2) {
        int [] A=new int[128];
        int[]B=new int[128];
        if(s1.length()!=s2.length())return false;
        for(int i=0;i<s1.length();i++) {
            int v1=s1.charAt(i);
            int v2=s2.charAt(i);
            A[v1]++;
            B[v2]++;
        }
        for(int i=0;i<A.length;i++) {
            if(A[i]!=B[i])return false;
        }
        return true;
        
    }
    public static String sort(String s) {
        char[]content=s.toCharArray();
        java.util.Arrays.sort(content);
        return new String(content);
    }
    public static boolean CheckPermutation2(String s1,String s2) {
        return sort(s1).equals(sort(s2));
    
    }

    public static void main(String[] args) {
        //String[]words= {"abcdb","dcbab","abbd"};
        //System.out.println(words[1]);
        //System.out.println(words[0]+","+words[1]+":"+CheckPermutation1(words[0], words[1]));
        //System.out.println(words[0]+","+words[2]+":"+CheckPermutation1(words[0], words[2]));
        String[][]pairs= {{"abcdb","dcbab"},{"abcdbd","dcbab"},{"aadf","knag"}};
        for(String[]pair:pairs) {
            String word1=pair[0];
            String word2=pair[1];
            long startTime1 = System.nanoTime();    //获取开始时间

            System.out.println(word1+","+word2+":"+CheckPermutation1(word1, word2));    //测试的代码段

            long endTime1 = System.nanoTime();    //获取结束时间

            System.out.println("程序1运行时间:" + (endTime1 - startTime1) + "ms");    //输出程序运行时间
            
            long startTime2 = System.nanoTime();    //获取开始时间

            System.out.println(word1+","+word2+":"+CheckPermutation2(word1, word2));    //测试的代码段

            long endTime2 = System.nanoTime();    //获取结束时间

            System.out.println("程序2运行时间:" + (endTime2 - startTime2) + "ms");    //输出程序运行时间
            System.out.println("\n"); 
        }
    }

}

 

string_Q2

原文:https://www.cnblogs.com/illusive/p/14695976.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!