//To check whether a given string is permutation of other string
public class Permutation{
public static void main(String args[]){
if(new Permutation().isPermutation("tiger","igert"))
System.out.println("Yes,strings are permutation of each other.");
else
System.out.println("No,strings aren't permutation of each other.");
}
public boolean isPermutation(String str1,String str2){
char arr[] = new char[255];
char brr[] = new char[255];
int j = 0;
if(str1.length() != str2.length())
return false;
for(int i=0 ; i<str1.length() ; i++)
{
arr[str1.charAt(i)]++;
brr[str2.charAt(i)]++;
}
//To check whether frequency of each character is same for both strings
for(j=0 ; j<arr.length && arr[j] == brr[j]; j++);
if(j!=255)
return false;
else
return true;
}
}
______________________________________________________________
Now implement the above with following constraint:
Do not use any additional data structure like array.
public class Permutation{
public static void main(String args[]){
if(new Permutation().isPermutation("tiger","igert"))
System.out.println("Yes,strings are permutation of each other.");
else
System.out.println("No,strings aren't permutation of each other.");
}
public boolean isPermutation(String str1,String str2){
char arr[] = new char[255];
char brr[] = new char[255];
int j = 0;
if(str1.length() != str2.length())
return false;
for(int i=0 ; i<str1.length() ; i++)
{
arr[str1.charAt(i)]++;
brr[str2.charAt(i)]++;
}
//To check whether frequency of each character is same for both strings
for(j=0 ; j<arr.length && arr[j] == brr[j]; j++);
if(j!=255)
return false;
else
return true;
}
}
______________________________________________________________
Now implement the above with following constraint:
Do not use any additional data structure like array.
//To check whether a given string is permutation of other string
public class Permutation1{
public static void main(String args[]){
if(new Permutation1().isPermut("ashish","shshii"))
System.out.println("These two are permutation of each other");
else
System.out.println("These aren't permutation of each other");
}
public boolean isPermut(String str1, String str2){
if(str1.length()!=str2.length())
return false;
for(int i=0 ; i<str1.length() ; i++)
{
if(str1.indexOf(str2.charAt(i)) == -1)
return false;
if(str2.indexOf(str1.charAt(i)) == -1)
return false;
}
return true;
}
public class Permutation1{
public static void main(String args[]){
if(new Permutation1().isPermut("ashish","shshii"))
System.out.println("These two are permutation of each other");
else
System.out.println("These aren't permutation of each other");
}
public boolean isPermut(String str1, String str2){
if(str1.length()!=str2.length())
return false;
for(int i=0 ; i<str1.length() ; i++)
{
if(str1.indexOf(str2.charAt(i)) == -1)
return false;
if(str2.indexOf(str1.charAt(i)) == -1)
return false;
}
return true;
}
No comments:
Post a Comment