2017-02-02 6 views
1

文字の配列を持っています。重複する文字は削除する必要があります。私はアルファベットの配列で文字列要素を比較しました。アルファベットの二重引用符のカウンターとして機能する別の配列があります。文字が複数回見つかった場合は、重複した文字を削除して要素を左に移動する必要があります。以下はコードです。コメントのある行にエラーが表示されます。 Javaでは、代入の左側が可変である必要があります。手伝ってくれますか?char要素の配列を左にシフトする方法

import java.util.ArrayList; 
import java.util.Scanner; 

public class removeduplicate { 

    public static void main (String args[]) 
    { 
     Scanner s=new Scanner(System.in); 
     String str="abbsded"; 

     String myChars="abcdefghijklmnopqrstuvwxyz"; 
     int[] myCounter=new int[26]; 

     for (int i=0; i<str.length(); i++) 
     { 
      for(int j=0; j<myChars.length(); j++) 
      { 
       if(str.charAt(i)==myChars.charAt(j)) 
       { 
        myCounter[j]++; 
        if (myCounter[j]>1) 
        { 
         System.out.println("duplication found in "+ str.charAt(i)); 
         for(int h=i; h<str.length();h++) 
         { 
          //this line does not work. 
          str.charAt(h)=str.charAt(h-1); 
         } 
        } 

       } 
      } 

     }//end for 

    } 

} 
+0

エラーをご報告いただけますか?また、文字列とアルファベット文字列があります。配列はあなたのint [] myCounter – Ishnark

+1

です。ループする方法が多い場合、ハッシュマップを使用してカウントを追跡してください。 –

+0

また、 'str'から重複を削除したい場合はhttp: /stackoverflow.com/questions/4989091/removing-duplicates-from-a-string-in-java – Ishnark

答えて

0

ハッシュマップを使用して、実装中に実行した文字を追跡することができます。その後、アルファベットの文字が表示されるたびに増加します。文字が以前に見られなかった場合にのみ、返された文字列に文字を追加します。

public static String removeDuplicates(String input) 
{ 
    String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
    input = input.toUpperCase(); 
    HashMap<Character, Integer> charData = new HashMap<>(); 

    //create the map to store counts of all the chars seen 
    for(int i = 0; i < alphabet.length(); i++) 
     charData.put(alphabet.charAt(i), 0); 

    String cleanedInput = ""; 

    for(int index = 0; index < input.length(); index++) 
    { 
     char letter = input.charAt(index); 
     if(charData.containsKey(letter)) 
     { 
      charData.put(letter, charData.get(letter) + 1); 
      //if count is 1 then its the first time we have seen it 
      if(charData.get(letter) == 1) 
      { 
       cleanedInput += letter; 
      } 
     } 
    } 
    return cleanedInput.toLowerCase(); 
} 

例コール

public static void main(String[] args) { 
    System.out.println(removeDuplicates("abbsded")); 
    System.out.println(removeDuplicates("abbsded!!!")); 
    System.out.println(removeDuplicates("hahahahahahahahahah")); 
}//main method 

出力

absde 
absde 
ha 

注:それは一度だけ文字を返し、アルファベットにない全く新しい文字がトリミングされた文字列では考慮されていません。

関連する問題