Java 字符串的排列和特定字符串的位置
我需要编写一个代码来查找字符串的所有排列,并查找给定的特定字符串的位置。我已经在stackoverflow中找到了这段代码来查找字符串的排列Java 字符串的排列和特定字符串的位置,java,string,permutation,Java,String,Permutation,我需要编写一个代码来查找字符串的所有排列,并查找给定的特定字符串的位置。我已经在stackoverflow中找到了这段代码来查找字符串的排列 public class StringCombi2 { public static void permutation(String str) { permutation("", str); } private static void permutation(String prefix, String str) { int n = str.lengt
public class StringCombi2 {
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
}
}
public static void main(String arsd[])
{
permutation("student");
}
}
公共类StringCombi2{
公共静态空置换(字符串str){
排列(“,str);
}
私有静态无效置换(字符串前缀、字符串str){
int n=str.length();
如果(n==0)System.out.println(前缀);
否则{
对于(int i=0;i
此代码打印字符串“Student”的所有可能排列
现在我需要找到字符串“Studten”的位置并打印它的位置(例如第i个位置)
我不知道怎么找到它有人能帮我吗
例如:
输出将像这样生成
学生
学生
studnet
学生
研究
斯特恩
斯图顿
斯图顿
斯图恩特
斯图恩特
.
.
字符串Studten在迭代4中生成。所以字符串“studen”的位置是4
我必须使用java代码找到这一点…如果您希望使用排列输出显示迭代,最简单的方法是创建一个全局计数器,使用排列打印计数器,然后立即递增计数器:
public class StringCombi2 {
private static int counter = 0; //create counter
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) {
System.out.println(counter + ": " + prefix); //print counter with permutation
counter++; // increment counter
} else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
}
}
public static void main(String arsd[]) {
permutation("student");
}
}
你所说的职位是什么意思?你能进一步解释吗?@Rishi当我运行这段代码时,每次迭代的输出都是这样打印的。。学生,学生,学生。我需要找出具体的文本studen是在哪个迭代中打印出来的。。。
public class StringCombi2 {
private static int counter = 0;
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) {
if (prefix.equals("studten")) {
System.out.println(prefix + " is at iteration: " + counter);
} else {
counter++;
}
} else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
}
}
public static void main(String arsd[]) {
permutation("student");
}
}
studten is at iteration: 4
studten is at iteration: 629