Checking if two strings are permutations of each other

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

How to determine if two strings are permutations of each other

相关标签:
30条回答
  • 2020-12-05 09:09
    • Sort the two strings's characters.
    • Compare the results to see if they're identical.

    Edit:

    The above method is reasonably efficient - O(n*log(n)) and, as others have shown, very easy to implement using the standard Java API. Even more efficient (but also more work) would be counting and comparing the occurrence of each character, using the char value as index into an array of counts.

    I do not thing there is an efficient way to do it recursively. An inefficient way (O(n^2), worse if implemented straightforwardly) is this:

    • If both strings consist of one identical character, return true
    • Otherwise:
      • remove one character from the first string
      • Look through second string for occurrence of this character
      • If not present, return false
      • Otherwise, remove said character and apply algorithm recursively to the remainders of both strings.
    0 讨论(0)
  • 2020-12-05 09:09

    Create a Hashmap with the characters of the first string as keys and the number of occurances as value; then go through the second string and for each character, look up the hash table and decrement the number if it is greater than zero. If you don't find an entry or if it is already 0, the strings are not a permutation of each other. Obviously, the string must have the same length.

    0 讨论(0)
  • 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");
               }       
        }
    

    }

    0 讨论(0)
  • 2020-12-05 09:09
    public class TwoStrgPermutation {
    
    public int checkForUnique(String s1, String s2)
    {
        int[] array1 = new int[256];
        int[] array2 = new int[256];
    
        array1 = arrayStringCounter(array1,s1);
        array2 = arrayStringCounter(array2,s2);
    
        if(Arrays.equals(array1, array2))
            return 0;
        else
            return 1;
    }
    
    public int[] arrayStringCounter(int[] array,String s)
    {
        int val;
        for(int i=0;i<s.length();i++)
        {
            val = (int)s.charAt(i);
            array[val]++;
        }
    
        return array;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);
        TwoStrgPermutation obj = new TwoStrgPermutation();
        try {
            String string1 = br.readLine();
            String string2 = br.readLine();
    
            int len1 = string1.length();
            int len2 = string2.length();
    
            if(len1==len2)
            {
                int result = obj.checkForUnique(string1,string2);
                if (result == 0){
                    System.out.println("yes it is a permutation");
                }
                else if (result >0)
                {
                    System.out.println("no it is not");
                }
            }
            else
            {
                System.out.println("no it is not");
            }
    
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
    }
    
    }
    
    0 讨论(0)
  • 2020-12-05 09:09
    bool is_permutation1(string str1, string str2) {
        sort(str1.begin(), str1.end());
        sort(str2.begin(), str2.end());
        for (int i = 0; i < str1.length(); i++) {    
            if (str1[i] != str2[i]) {
                return false;
            }
        }
        return true;
    }
    
    0 讨论(0)
  • 2020-12-05 09:10

    You can try to use XOR, if one string is a permeation of the other, they should have essentially identical chars. The only difference is just the order of chars. Therefore using XOR trick can help you get rid of the order and focus only on the chars.

    public static boolean isPermutation(String s1, String s2){
        if (s1.length() != s2.length()) return false;
        int checker = 0;
        for(int i = 0; i < s1.length();i++ ){
            checker ^= s1.charAt(i) ^ s2.charAt(i);
        }
    
        return checker == 0;
    }
    
    0 讨论(0)
提交回复
热议问题