Checking if two strings are permutations of each other

前端 未结 30 1028
感情败类
感情败类 2020-12-05 08:19

How to determine if two strings are permutations of each other

30条回答
  •  天命终不由人
    2020-12-05 09:09

                 import java.io.*;
                          public class permute 
                        {
                                  public static String sort(String s)
                                  {
                                         char[] str = s.toCharArray();
                                        java.util.Arrays.sort(str);
                                        return new String(str);
                                  }
                          public static boolean permutation(String s,String t)
                         {
                                if(s.length()!=t.length())
                               {
                                       return false;
                               }
                                       return sort(s).equals(sort(t));
                         }
        public static void main(String[] args)            throws IOException
        {
               BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
               String string = null;
               boolean x=true;
               System.out.println("Input String:");
               string = bf.readLine();
               System.out.println("Input another String:");
               String result = bf.readLine();
               String resultant = sort(string);
               if(x==permutation(result,resultant))
               {
                        System.out.println("String"+" "+"("+result+")"+"is a permutation of String"+" "+"("+string+")");
               }
               else
               {
                        System.out.println("Sorry No anagram found");
               }       
        }
    

    }

提交回复
热议问题