1.3 Given two strings, write a method to decide if one is a permutation of the other.
Maybe the word 'permutation' is unfamiliar to you. Actually, it means the lengths of the two strings are the same. So you don't need to nest any iteration. It is different from computing the substring. Please pay attention.
We have two ways to solve this question.
1. Sort the string : In order to use sort(), we need to transform s1 to a array
package javaapplication1;
import java.io.*;
/**
*
* @author user
*/
public class JavaApplication1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String s1="",s2="";
InputStreamReader input= new InputStreamReader(System.in);
BufferedReader reader=new BufferedReader(input);
System.out.println("Please type in the string1");
try{
s1=reader.readLine();
}
catch(IOException e)
{
e.printStackTrace();
}
System.out.println("Please type in the string2");
try{
s2=reader.readLine();
}
catch(IOException e)
{
e.printStackTrace();
}
char a[]= s1.toCharArray();
char b[]= s2.toCharArray();
java.util.Arrays.sort(a);
java.util.Arrays.sort(b);
if(s1.length()!=s2.length())
System.out.println("no permutation!");
for(int i=0;i<s1.length();i++) //you could transform sorted array to string and use equal() to compare string. Then don't need to use iteration.
{
if(a[i]!=b[i])
{
System.out.println("no permutation!");
return;
}
}
System.out.println("yes!");
}
}
2.Count the characters
Use the value of character as the index of the value
In your interview, you should always check with your interviewer about the size of the character set. We assumed that the character set was ASCII. So the size of index is 256.