如何在循环中显示单词,在每次迭代时删除最后一个字母

How to display the Word in a Loop removing the last letter at each iteration

问题陈述:

Create a program that initializes a word in a character array (this becomes your stack) and displays the word removing the last letter on the stack.

示例

输入:

LONELY

输出:

LONELY
LONEL
LONE
LON
LO
L

这是我的代码,我只能打印数组中的字符。

但是我还没有想出一个解决方案来继续删除最后一个字母,就像输出显示的那样。

并且可能需要它符合逻辑。

public static void main(String[] args) {
    char word[] = {'S', 'T', 'U', 'C', 'K'};
    int len = word.length;
        
    for (int x = 0; x < len; x++) {
        System.out.print(word[x]);
    }
}

您可以使用嵌套 for 循环。

内循环的变量指向一个特定的字符。而外层循环中定义的变量表示当前行需要跳过的字符数。

语句System.out.println()在每个内循环后执行,并将输出推进到下一行。

public static void main(String[] args) {
    char word[] = {'L', 'O', 'N', 'E', 'L', 'Y'};
    int len = word.length;
    
    for (int i = 0; i < len; i++) {
        for (int j = 0; j < len - i; j++) {
            System.out.print(word[j]); // printing a row
        }
        System.out.println(); // advancing output to the next line
    }
}

但是,如果您的挑战意味着您需要创建一个将由字符数组支持的堆栈数据结构的实现,那么任务就有点复杂了。

下面的代码旨在提供有关如何操作的一般思路。

栈的实现中必须存在三个重要的方法:

  • push() - 添加新元素(在方法主体中我提供了说明但省略了此实现,因此您有机会获得 hands-on经验);
  • pop() - 从栈顶移除元素并返回;
  • peek() - returns 堆栈顶部的元素而不删除它。

此外,我添加了 isEmpty()print() 方法的实现,可用于检查堆栈是否为空并打印其内容,正如它们的名称所暗示的那样。

class CharacterStack {
    private char[] letters;
    private int pos = -1;
    
    public CharacterStack(int size) {  // size is passed as an argument
        this.letters = new char[size]; // creating an empty array of characters
    }
    
    public CharacterStack(char[] letters) { // array of characters is passed as an argument
        this.letters = letters;
        this.pos = letters.length - 1; // position at the top of the stack - the greatest valid index of the array
    }
    
    public void push(char letter) {
        /* to do:
          1. check the length of the array
          2. if current position doesn't fit in to it create a new array with greater length
          3. copy the contents of the previous array into a new array
          4. re-assign the variable `letters` to be a newly created array
         */
    }
    
    public char pop() { // removing the element from the top of the stack and returning it
//        return letters[pos--]; a concise equivalent of the lines below
        
        char result = letters[pos];
        pos--;
        return result;
    }
    
    public char peek() { // returning the element from the top of the stack without removing it
        return letters[pos];
    }
    
    public boolean isEmpty() {
        return pos == -1;
    }
    
    public void print() {
        for (int i = 0; i <= pos; i++) {
            System.out.print(letters[i]);
        }
    }
}

main() - 演示

public static void main(String[] args) {
    char[] word = {'L', 'O', 'N', 'E', 'L', 'Y'};
    int len = word.length;
    CharacterStack stack = new CharacterStack(word);
    
    while (!stack.isEmpty()) {
        stack.print();        // printing the contents of the stack

        System.out.println(); // advancing output to the next row
        stack.pop();          // removing the element from the top of the stack
    }
}

输出

LONELY
LONEL
LONE
LON
LO
L

Java Stack Javadoc 说(部分)

A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class. For example: Deque<Integer> stack = new ArrayDeque<Integer>();

对于你的情况,我相信你想要一个 Deque<Character>。将数组中的所有值推入 Deque,然后在嵌套循环中迭代 Deque。像,

char[] word = "LONELY".toCharArray();
Deque<Character> stack = new ArrayDeque<>();
for (int i = 0; i < word.length; i++) {
    stack.push(word[i]);
}
while (!stack.isEmpty()) {
    Iterator<Character> iter = stack.descendingIterator();
    while (iter.hasNext()) {
        System.out.print(iter.next());
    }
    System.out.println();
    stack.pop();
}

哪些输出(按要求)

LONELY
LONEL
LONE
LON
LO
L