簡體   English   中英

如何在循環中顯示單詞,在每次迭代時刪除最后一個字母

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

問題陳述:

創建一個程序來初始化字符數組中的一個單詞(這將成為您的堆棧)並顯示刪除堆棧中最后一個字母的單詞。

例子

輸入:

LONELY

Output:

LONELY
LONEL
LONE
LON
LO
L

所以這是我的代碼,我只能打印數組上的字符。

但是我還沒有想出一個解決方案來繼續刪除最后一個字母,就像 output 的顯示方式一樣。

並且可能需要它是合乎邏輯的。

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循環。

內循環的變量指向一個特定的字符。 而外層循環中定義的變量表示當前行需要跳過的字符數。

Statement System.out.println()在每個內部循環之后執行,並將 output 推進到下一行。

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() - 演示

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

Java Stack Javadoc說(部分)

Deque接口及其實現提供了一組更完整和一致的 LIFO 堆棧操作,應優先使用此 class。例如: 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM