栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用迭代对字符串进行排列

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用迭代对字符串进行排列

在我的相关问题评论之后,这是一个Java实现,可以使用Counting QuickPerm
Algorithm
来完成您想要的事情:

public static void combString(String s) {    // Print initial string, as only the alterations will be printed later    System.out.println(s);       char[] a = s.toCharArray();    int n = a.length;    int[] p = new int[n];  // Weight index control array initially all zeros. Of course, same size of the char array.    int i = 1; //Upper bound index. i.e: if string is "abc" then index i could be at "c"    while (i < n) {        if (p[i] < i) { //if the weight index is bigger or the same it means that we have already switched between these i,j (one iteration before). int j = ((i % 2) == 0) ? 0 : p[i];//Lower bound index. i.e: if string is "abc" then j index will always be 0. swap(a, i, j); // Print current System.out.println(join(a)); p[i]++; //Adding 1 to the specific weight that relates to the char array. i = 1; //if i was 2 (for example), after the swap we now need to swap for i=1        }        else {  p[i] = 0;//Weight index will be zero because one iteration before, it was 1 (for example) to indicate that char array a[i] swapped. i++;//i index will have the option to go forward in the char array for "longer swaps"        }    }}private static String join(char[] a) {    StringBuilder builder = new StringBuilder();    builder.append(a);    return builder.toString();}private static void swap(char[] a, int i, int j) {    char temp = a[i];    a[i] = a[j];    a[j] = temp;}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/595714.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号