Java程式刪除給定字串中的重複字元


Set介面不允許重複元素,因此,建立一個Set物件,並嘗試使用add()方法將每個元素新增到其中,如果元素重複,則此方法返回false -

如果您嘗試將陣列的所有元素新增到Set中,它只接受唯一元素,因此,要查詢給定字串中的重複字元。

問題陳述

給定一個字串,編寫一個Java程式來刪除給定字串中的重複字元 -

輸入

TUTORIALSPOINT

輸出

Indices of the duplicate characters in the given string :: 
Index :: 2 character :: T
Index :: 10 character :: O
Index :: 11 character :: I
Index :: 13 character :: T

從給定字串中刪除重複字元的步驟

以下是從給定字串中刪除重複字元的步驟 -

  • 匯入所有必要的類。
  • 將字串轉換為字元陣列。
  • 嘗試使用add方法將上面建立的陣列的元素插入到雜湊集中。
  • 如果新增成功,此方法返回true。
  • 由於Set不允許重複元素,因此當您嘗試插入重複元素時,此方法返回0
  • 列印這些元素。

Java程式刪除給定字串中的重複字元

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class DuplicateCharacters {
 public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the required string value ::");
String reqString = sc.next();
char[] myArray = reqString.toCharArray();
System.out.println("indices of the duplicate characters in the given string :: ");
Set set = new HashSet();

for(int i=0; i<myArray.length; i++){
 if(!set.add(myArray[i])){
System.out.println("Index :: "+i+" character :: "+myArray[i]);
 }
}
 }
}

輸出

Enter the required string value ::
TUTORIALSPOINT
Indices of the duplicate characters in the given string :: 
Index :: 2 character :: T
Index :: 10 character :: O
Index :: 11 character :: I
Index :: 13 character :: T

程式碼解釋

程式首先匯入必要的類和介面:HashSetScanner和來自java.util包的Set。main方法初始化一個Scanner來讀取使用者的輸入字串,然後將其轉換為字元陣列。HashSet用於儲存唯一字元,利用其不允許重複的特性。

程式使用for迴圈遍歷字元陣列,使用HashSet的add()方法嘗試新增每個字元。如果字元已存在,add()返回false,程式列印索引和重複字元。此方法確保所有重複項都能被有效地識別和輸出,利用HashSet來最佳化效能,避免重複元素。 

更新於: 2024年7月31日

2K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告