[英]Permutations of a string using a stack in Java
我在弄清楚为什么我的代码无法正常工作时遇到了问题。 该代码应该将字符串压入堆栈。 那么它将在字符串前面放置一个“ +”号。 (例如[+ dog]。接下来,它弹出堆栈。它将“ +”符号右侧的字符逐个移动到字符串的左侧(例如[d + og] [o + dg] [g + do]并将它们压入堆栈。这会反复进行,直到字符串的所有排列都以加号结束(例如[dog +] [dgo +] [god +] [gdo +] [odg +] [ogd + ]然后查看堆栈上的字符串是否在末尾带有“ +”号,如果是,它将打印出该语句,这是我的代码:
我遇到的问题是我的其他else语句。 我无法使字符移动到“ +”符号的另一侧。
import java.util.Scanner;
import java.util.Stack;
import java.util.*;
import java.lang.*;
public class string_Perm{
public static void main(String[] args) {// this takes user input for a string and runs it through the program
Scanner inputString = new Scanner(System.in);
String userInput;
System.out.print("Enter a String: ");
userInput = inputString.next();
// test print statement below
//System.out.println(userInput);
PermString(userInput);
}
public static void PermString(String userInput){
Stack permStack = new Stack();
permStack.push("+" + userInput);//this pushes the user input string onto the stack.
// test print statement below
//System.out.println(permStack);
while(!permStack.isEmpty()){
String currentItem = (permStack.pop().toString());// it then pops the top of the stack while the stack isn't empty.
if(currentItem.endsWith("+")){
currentItem.substring(0,currentItem.length()-1);// if the string ends with a +, you print the string without the + at the end
System.out.println(currentItem);
}
else{// this else statement is where i am having trouble its supposed to split the string at the plus sign and then move each char one by one to infront of the "+" sign, then push it onto the stack.
String[] charArray = currentItem.split("\\+");
System.out.println(charArray[charArray.length-1]);
for(int i = 0;i <= charArray.length; i++){
String getWord = charArray[charArray.length - 1];
String addWord = (charArray[i] + "+" + getWord.substring(0,i) + getWord.substring(i,0));
System.out.println(addWord);
permStack.push(addWord);
}
}
}
}
}
欢迎对此代码或其他方法进行任何更改。 提前致谢。
您的索引有问题。 我的建议:
charArray
第二个字符串的charArray
(charArray保存字符串而不是字符!)。 getWord.substring()
。 这是我建议的for循环代码:
String[] charArray = currentItem.split("\\+");
for(int i = 0; i < charArray[1].length(); i++){
String getWord = charArray[charArray.length - 1];
StringBuilder sb = new StringBuilder(getWord);
String addWord = (getWord.charAt(i) + charArray[0] + "+" + sb.deleteCharAt(i).toString());
System.out.println(addWord);
permStack.push(addWord);
}
试试这个,让我知道这是否是您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.