Java程式查詢字元流中的第一個非重複字元


在一個字串中查詢第一個非重複字元是一個常見的程式設計問題。它涉及查詢在字串中只出現一次的第一個字元。這項任務有助於理解如何在Java中操作字串和使用基本的資料結構

問題陳述

給定一個字串,找出第一個不重複的字元。如果所有字元都重複,則表明沒有非重複字元。

輸入

tutorialspoint

輸出

The first non-repeating character of the string is T

從字元流中查詢第一個非重複字元的步驟

以下是從字元流中查詢第一個非重複字元的步驟:

  • 使用ArrayList進行初始化,以跟蹤可能是非重複的字元。
  • 使用布林陣列標記出現多次的字元。
  • 遍歷字串中的每個字元,如果字元不重複且不在列表中,則將其新增到列表中;如果在列表中,則將其從列表中移除並將其標記為重複。
  • 列表中的第一個字元是第一個非重複字元。
  • 如果列表為空,則表示未找到非重複字元。

示例

要從字元流中查詢第一個非重複字元,Java程式碼如下:

import java.util.ArrayList;
import java.util.List;

public class Demo {
    final static int max_chars = 256;

    static void non_repeating_char() {
        List<Character> my_list = new ArrayList<Character>();
        boolean[] repeat = new boolean[max_chars];
        String my_str = "tutorialspoint";

        for (int i = 0; i < my_str.length(); i++) {
            char x = my_str.charAt(i);
            if (!repeat[x]) {
                if (!my_list.contains(x)) {
                    my_list.add(x);
                } else {
                    my_list.remove((Character) x);
                    repeat[x] = true;
                }
            }
        }

        if (my_list.size() != 0) {
            System.out.println("The first non-repeating character is " + my_list.get(0));
        } else {
            System.out.println("No non-repeating character found");
        }
    }

    public static void main(String[] args) {
        non_repeating_char();
    }
}

輸出

The first non-repeating character of the string is u

程式碼解釋

名為Demo的類包含一個名為non_repeating_char 的函式。建立一個列表並定義一個字串。遍歷此字串,檢查每個字元,並將它的計數儲存為布林變數,儲存在一個名為repeat陣列中。如果重複則值為true,否則為false。呼叫主函式,並在控制檯上顯示相關訊息。

更新於:2024年7月23日

1K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.