[Interview] Check Permutation
--------------------------------------------------------------------------------------------------------------------------
Question:
Given 2 Strings, write a method to decide if one is a permutation of the other.
--------------------------------------------------------------------------------------------------------------------------
Idea 1:
count the number of each character in first string and check if the number of each character in the 2nd string is the same as the 1st string.
Solution 1:
--------------------------------------------------------------------------------------------------------------------------
Idea 2:
Sort the strings and check if they are same
Solution 2:
Given 2 Strings, write a method to decide if one is a permutation of the other.
--------------------------------------------------------------------------------------------------------------------------
Idea 1:
count the number of each character in first string and check if the number of each character in the 2nd string is the same as the 1st string.
Solution 1:
public class Solution{
boolean checker(String str1, String str2)
{
if (str1.length() != str2.length()) return false;
int[] helper = new int[256];
for(int i = 0 ; i<str1.length();i++)
{
int index = str1.charAt(i);
helper[index]++;
}
for(int i = 0 ; i<str2.length();i++)
{
int index = str2.charAt(i);
helper[index]--;
if(helper[index]<0) return false;
}
return true;
}
}
--------------------------------------------------------------------------------------------------------------------------
Idea 2:
Sort the strings and check if they are same
Solution 2:
public class Solution{
boolean checker2(String str1, String str2)
{
if (str1.length() != str2.length()) return false;
return sort(str1).equals(sort(str2));
}
String sort(String str)
{
char[] c = str.toCharArray();
Arrays.sort(c);
return new String(c);
}
}
--------------------------------------------------------------------------------------------------------------------------
Video Explanation
Comments
Post a Comment