-1

* Interviewstreet.comからの質問 (文字列順列) *

  • 2 つの文字列を指定して、一方が他方の順列であるかどうかを判断するメソッドを作成します。ソリューションでは、大文字と小文字の区別と空白を重要なものとして考慮する必要があります。

  • オブジェクトのセットの順列は、それらのオブジェクトを特定の順序に配置することです。たとえば、文字列「abc」には、「abc」、「acb」、「bac」、「bca」、「cab」、「cba」の 6 つの順列があります。

  • 出力: 2 つの文字列が互いの順列である場合は 1 を返します。2 つの文字列が互いに順列でない場合は 0 を返します。

  • abc acb cab cba bac bca

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

1 に答える 1