(String Permutation)来自interviewstreet.com

时间:2013-05-30 17:39:59

标签: string permutation

来自interviewstreet.com的

* 问题(字符串排列) *

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

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

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

  • abc acb cab cba bac bca

import java.io。*;

import 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;}}

1 个答案:

答案 0 :(得分:2)

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