-1

*来自 interviewstreet.com 的问题(字符串排列) *

  • 给定两个字符串,编写一个方法来确定一个是否是另一个的排列。您的解决方案应考虑区分大小写和空格。

  • 一组对象的排列是这些对象按特定顺序排列。例如,字符串“abc”有六种排列,分别是“abc”、“acb”、“bac”、“bca”、“cab”和“cba”。

  • 输出:如果两个字符串是彼此的排列,则返回 1。如果两个字符串不是彼此的排列,则返回 0。

  • abc acb 出租车 cba bac bca

导入java.io.*;

导入 java.util.*;

公共类解决方案{

私有集合排列;

public static void main(String args[] ) throws Exception {
 //   Scanner sc = new Scanner(System.in);
    //String string1 = sc.nextLine();
    //String string2 = sc.nextLine();

String string1 = "str";
    String string2 = "str";

    Solution solution = new Solution();
    int output = solution.permutation(string1, string2);
    System.out.println(output);
}

public  void stringPermuation(String s1, String s2) {

if (s2.length() > 0) {

for (int i = 0; i < s2.length(); i++) {
    System.out.println(s1 + s2.charAt(i)+","+ s2.substring(0, i)+" +"+ s2.substring(i + 1));

    stringPermuation(s1 + s2.charAt(i),
        s2.substring(0, i) + s2.substring(i + 1));
    }}
else{
    permutations.add(s1);
    System.out.println(s1);
}
}

public Set stringPermuation(String s) {
permutations = new HashSet<String>();
stringPermuation("", s);
return permutations;
}



private  int permutation(String string1, String string2) {
int result = 0;
 Set<String> setString1 = stringPermuation(string1);
 Set<String> setString2 = stringPermuation(string2);
    // create an iterator

     System.out.println("There are total of " + setString1.size() + " permutations in String1:");
     System.out.println("There are total of " + setString2.size() + " permutations in String2:");

     if(setString1.size() == setString2.size())
        result=IterateSet(setString1,setString2);

    //Return 1 if string1 is a permutation of string2
    //Return 0 if string1 is not a permutation of string2
return result;
}

public  int IterateSet(Set setString1,Set setString2){
    int  i=  0;
    Iterator<String> it = setString1.iterator();
    while (it.hasNext()) {
        if(setString2.contains(it.next()) && i == 0)
         i=1;
    }
return i;}}
4

1 回答 1

2

...对两个字符串的字符进行排序(按字典顺序),如果两个排序后的字符串相等,则原件是彼此的排列。

于 2013-05-30T17:49:11.063 回答