Checking if two strings are permutations of each other

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

How to determine if two strings are permutations of each other

相关标签:
30条回答
  • 2020-12-05 09:03
        public static boolean isPermutation(String s1, String s2) {
        if (s1.length() != s2.length()) {
            return false;
        }else if(s1.length()==0 ){
            return true;
        }
        else if(s1.length()==1){
            return s1.equals(s2);
        }
        char[] s = s1.toCharArray();
        char[] t = s2.toCharArray();
    
        for (int i = 0; i < s.length; i++) {
            for (int j = 0; j < t.length; j++) {
    
                if (s.length == s1.length() && (i == 0 && j == t.length - 1) && s[i] != t[j]) {
                    return false;
                }
                if (s[i] == t[j]) {
                    String ss = new String(s);
                    String tt = new String(t);
                    s = (ss.substring(0, i) + ss.substring(i + 1, s.length)).toCharArray();
                    t = (tt.substring(0, j) + tt.substring(j + 1, t.length)).toCharArray();
    
                    System.out.println(new String(s));
                    System.out.println(new String(t));
    
                    i = 0;
                    j = 0;
                }
            }
        }
        return s[0]==t[0] ;
    }
    

    This solution works for any charset. With an O(n) complexity.

    The output for: isPermutation("The Big Bang Theory", "B B T Tehgiangyroeh")

    he Big Bang Theory
    B B  Tehgiangyroeh
    e Big Bang Theory
    B B  Tegiangyroeh
     Big Bang Theory
    B B  Tgiangyroeh
    Big Bang Theory
    BB  Tgiangyroeh
    ig Bang Theory
    B  Tgiangyroeh
    g Bang Theory
    B  Tgangyroeh
     Bang Theory
    B  Tangyroeh
    Bang Theory
    B Tangyroeh
    Bng Theory
    B Tngyroeh
    Bg Theory
    B Tgyroeh
    B Theory
    B Tyroeh
    BTheory
    BTyroeh
    Bheory
    Byroeh
    Beory
    Byroe
    Bory
    Byro
    Bry
    Byr
    By
    By
    B
    B
    true
    
    0 讨论(0)
  • 2020-12-05 09:04

    To put @Michael Borgwardt's words in to code:

    public boolean checkAnagram(String str1, String str2) {
    
        if (str1.length() != str2.length())
          return false;
    
        char[] a = str1.toCharArray();
        char[] b = str2.toCharArray();
    
        Arrays.sort(a);
        Arrays.sort(b);
    
        return Arrays.equals(a, b);
    }
    
    0 讨论(0)
  • 2020-12-05 09:07
    public boolean permitation(String s,String t){
          if(s.length() != t.length()){
              return false;
              }
    
           int[] letters = new int[256];//Assumes that the character set is ASCII
           char[] s_array = s.toCharArray();
    
           for(char c:s_array){         /////count number of each char in s
                 letters[c]++;
            }
           for(int i=0;i<t.length();i++){
                 int c = (int)t.charAt(i);
                 if(--letters[c]<0){
                      return false;
                 }
            }
            return true;
    }
    
    0 讨论(0)
  • 2020-12-05 09:08
    >>>def isPermutation = lambda x, y: set([i for i in x]) == set([j for j in x])
    >>>isPermutation("rasp", "spar")
    >>>True
    
    0 讨论(0)
  • 2020-12-05 09:08

    It can be done by using a Dictionary in C#. A basic implementation is like :

        private static bool IsPermutation(string str1, string str2)
        {
            if (str1.Length != str2.Length)
                return false;
    
            var dictionary = new Dictionary<char, int>();
    
            foreach(var x in str1)
            {
                if (dictionary.ContainsKey(x))
                    dictionary[x] += 1;
                else
                    dictionary.Add(x, 1);
            }
    
            foreach (var y in str2)
            {
                if (dictionary.ContainsKey(y))
                {
                    if (dictionary[y] > 0)
                        dictionary[y] -= 1;
                    else
                        return false;
                }
                else
                    return false;
            }
    
            foreach(var el in dictionary)
            {
                if (el.Value != 0)
                    return false;
            }
    
            return true;
        }
    

    Time Complexity is O(n), linear solution.

    0 讨论(0)
  • 2020-12-05 09:08

    I wanted to give a recursive solution for this problem as I did not find any answer which was recursive. I think that this code seems to be tough but if you'll try to understand it you'll see the beauty of this code. Recursion is sometimes hard to understand but good to use! This method returns all the permutations of the entered String 's' and keeps storing them in the array 'arr[]'. The value of 't' initially is blank "" .

    import java.io.*;
    class permute_compare2str
    {
        static String[] arr= new String [1200];
        static int p=0;
        void permutation(String s,String t)
        {
            if (s.length()==0)
            {
                arr[p++]=t;
                return;
            }
            for(int i=0;i<s.length();i++)
                permutation(s.substring(0,i)+s.substring(i+1),t+s.charAt(i));
        }
        public static void main(String kr[])throws IOException
        {
            int flag = 0;
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter the first String:");
            String str1 = br.readLine();
            System.out.println("Enter the second String:");
            String str2 = br.readLine();
            new permute_compare2str().permutation(str1,"");
            for(int i = 0; i < p; ++i)
            {
                if(arr[i].equals(str2))
                {
                    flag = 1;
                    break;
                }
            }
            if(flag == 1)
                System.out.println("True");
            else
            {
                System.out.println("False");
                return;
            }
        }
    }
    

    One limitation that I can see is that the length of the array is fixed and so will not be able to return values for a large String value 's'. Please alter the same as per the requirements. There are other solutions to this problem as well.

    I have shared this code because you can actually use this to get the permutations of a string printed directly without the array as well.

    HERE:

    void permutations(String s, String t)
        {
            if (s.length()==0)
            {
                System.out.print(t+" ");
                return;
            }
            for(int i=0;i<s.length();i++)
                permutations(s.substring(0,i)+s.substring(i+1),t+s.charAt(i));
        }
    

    Value of 's' is the string whose permutations is needed and value of 't' is again empty "".

    Reference: Introduction to Programming in Java

    0 讨论(0)
提交回复
热议问题