Use a stack to return a list containing all permutations of a given string. Hint
ID: 3761283 • Letter: U
Question
Use a stack to return a list containing all permutations of a given string.
Hint: Suppose you want to find all permutations of the string leaf.
Push the string +leaf on the stack.
While the stack is not empty
Pop off the top of the stack.
If that string ends in a + (such as fale+)
Remove the + and add the string to the list of permutations.
Else
Remove each letter in turn from the right of the +.
Insert it just before the +.
Push the resulting string on the stack.
Implement in Java a countOfPermutations method with the following signature:
public List<String> countOfPermutations(String word);
Explanation / Answer
import java.util.*;
public class permutations {
public List<String> countOfPermutations(String word) {
List<String> permList = new ArrayList<String>();
Stack<String> myStack = new Stack<String>();
myStack.push(word);
while (!myStack.empty()) {
myStack.pop();
if (word.endsWith("+")) {
permList.add(word.substring(0, word.length() - 1));
} else {
}
}
return permList;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.