Check Permutation

 

For a given two strings, 'str1' and 'str2', check whether they are a permutation of each other or not.

Sample Input 1:
abcde
baedc
Sample Output 1:
true
Approach 1- (Time limit might exceed in some test cases)
public class Solution {

	public static boolean isPermutation(String str1, String str2) {
    	
        int n=str1.length();
        int l=str2.length();
			 int c=0;
			 if(n!=l)
			 return false;
			 for(int i=0;i<n;i++)
			 {
			 for(int j=0;j<l;j++)
			 {
			 	if(str1.charAt(i)==str2.charAt(j))
			 {
			 c++;
			 }}
			 }
			 if(c==n)
			 {
			 return true;
			 }
			 return false;
}}
        
Approach 2 - 
import java.util.Arrays;
public class Solution {

	public static boolean isPermutation(String str1, String str2) {
    	
        int n=str1.length();
        int l=str2.length(); 
            if(n!=l)
			return false;
        char a[]= str1.toCharArray();
        char b[]= str2.toCharArray();
        
        Arrays.sort(a);
        Arrays.sort(b);
        
        return Arrays.equals(a,b);
	}
}

Comments

Popular posts from this blog

Minimum Length Word

Check Number Sequence

Star Pattern