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

发布于 2025-01-26 21:20:03 字数 556 浏览 3 评论 0原文

问题声明:

创建一个在字符阵列中初始初始单词的程序(this 成为您的堆栈),并显示删除最后一个字母的单词 堆栈。

示例

输入:

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]);
    }
}

Problem statement:

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.

Example

Input:

LONELY

Output:

LONELY
LONEL
LONE
LON
LO
L

So this is my code and I have only able to print the character on the array.

But I haven't come up of a solution to keep removing the last letter, just like how the output would show.

And probably need it to be logical.

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]);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我的黑色迷你裙 2025-02-02 21:20:03

您可以将嵌套用于循环。

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

语句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() - 添加了新元素(在方法主体中,我提供了指令,但遗漏了此实现,这样您就有机会获得动手体验);
  • pop() - 从堆栈顶部删除元素并将其返回;
  • peek() - 从堆栈顶部返回元素而无需删除。

另外,我添加了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() -demo

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

You can use nested for loop.

The variable of the inner loop points to a particular character. And the variable defined in the outer loop denotes the number of characters that need to be skipped in the current row.

Statement System.out.println() is executed after each inner loop and advances the output to the next line.

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
    }
}

But if your challenge implies that you are expected to create an implementation of the stack data structure that will be backed by the character array, that a bit more complicated task.

The code below is meant to provide the general idea on how to it.

There are three important methods that have to be present in the implementation of stack:

  • push() - adds new element (in the method body I've provided the instructions but left out this implementation, so that you're given a chance to obtain a hands-on experience);
  • pop() - removes the element from the top of the stack and returning it;
  • peek() - returns the element from top of the stack without removing it.

Also, I added implementations of isEmpty() and print() methods that could be used to check whether the stack is empty and to print its contents, as their names suggest.

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() - demo

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
    }
}

Output

LONELY
LONEL
LONE
LON
LO
L
别忘他 2025-02-02 21:20:03

java stack> stack stack /a>说(部分)

Deque 接口及其实现,应优先使用该类别。例如:
Deque&lt; Integer&gt; stack = new arraydeque&lt; integer&gt;();

在您的情况下,我相信您需要一个Deque&lt; partinal&gt;。将所有值从数组中推入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

The Java Stack Javadoc says (in part)

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>();

For your case, I believe you want a Deque<Character>. Push all the values from the array into the Deque and then iterate the Deque in a nested loop. Something like,

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();
}

Which outputs (as requested)

LONELY
LONEL
LONE
LON
LO
L
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文