繁体   English   中英

Java:获取不倒置的字符串数组对的所有组合的算法

[英]Java: algorithm to obtain all combinations of pairs of an array of strings not inverted

我有一个字符串数组:

List<String> st=new ArrayList<String>();
st.add("Massachusetts institute"); 
st.add("of");
st.add("Technology");

我想实现一种算法,以获取不颠倒的字符串数组对的所有组合,从而获得所有这些组合:

-Massachusetts institute
-of
-Technology
-Massachusetts institute, of
-Massachusetts institute, Technology
-of, Technology
-Massachusetts institute, of, Technology

自然也可以使用更长的字符串,例如:

List<String> st=new ArrayList<String>();
st.add("Massachusetts institute"); 
st.add("of");
st.add("Technology");
st.add("MIT");

我应该得到:

-Massachusetts institute
-of
-Technology
-MIT
-Massachusetts institute, of
-Massachusetts institute, Technology
-Massachusetts institute, MIT
-of, Technology
-of, MIT
-Technology, MIT
-Massachusetts institute, of, Technology
-Massachusetts institute, of, MIT
-Massachusetts institute, Technology, MIT
-Massachusetts institute, of, Technology, MIT

没有格式化空格,以下是我所做的事情:

// Your code
List<String> st=new ArrayList<String>();
st.add("Massachusetts institute "); 
st.add("of ");
st.add("Technology ");
st.add("MIT");
/* Added a few more to st for my own tests - see IDEONE link below */
//-------------------------------------------------------------------

/* Additional code */
Set<String> combs = new HashSet<String>(); // Set of matches default 16 spaces
/* The code should work even if the size goes above 16 - tried it in IDEONE */

int p = st.size(); // Get the endpoint

for(int i =0; i<p; i++){
     for(int j=i+1; j<p; j++) {
         combs.add(st.get(i) + st.get(j));
    }
}
Iterator g = combs.iterator();

while(g.hasNext()) {
    System.out.println(g.next());
}
}
/************************************************/

演示在这里-http://ideone.com/K92Xwi另外,在阅读了一些相关的评论之后,PermutationIterator的Apache库,Combinatorics的Google代码库等也应该为您提供帮助。 但是上面的代码只使用主要的Java。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM