2017-04-26 3 views
0

以下は私のコードです。問題は、指定された文字列内の最初のユニークな(繰り返されない)文字を見つけることです。私はJavaの初心者です。今はコードをデバッグする方法が不思議です......私の限られた知識私はどのようにデバッグを開始するかわからない......ありがとう!最初のユニークな文字を取得するには?

public class Solution { 
     public int firstUniqChar(String s) { 
     //My idea without referring to any other solution. 
     //put the all character into the hashmap, and delete the key if 
     //there is duplicate value, then get the first key of 
     //the remaining map, that is the smallest index of the unique 
     //character; 
     Map<Integer,Character> hmap=new HashMap<Integer,Character>(); 
      int index = 0; 
      for (int i = 0; i < s.length(); i++){ 
       //int value=(int)((Integer)map.get(a[i])); 
       char charI = s.charAt(i); 
       index ++; 
       hmap.put(index, charI); 
       //Error: cannot find this method; 
       while (hmap.ContainsValue(charI)){ 
        hkey = charI.getkey(); 
        hkey.remove(); 

       } 
       } 
     //to return the index of the first key in the hashmap. 
     //Error: illegal start of type; 
      return hmap.get(hmap.keySet().toArray()[0]); 
     } 
} 
+0

この方法は、あなたは、文字列の最初のユニークなキャラクターを見つけますか?デバッガの起動方法はツールによって異なります。しかし、プログラムのいくつかの場所にテスト出力を追加して、変数の値をチェックすることもできます。また、結果が文字でなければならない場合、なぜメソッドはintを返しますか? – Henry

+0

ようこそスタックオーバーフロー!デバッガの使い方を学ぶ必要があるようです。 [補完的なデバッグ手法](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)にご協力ください。その後も問題が残っている場合は、問題を示す[最小限の、完全で実証可能な例](http://stackoverflow.com/help/mcve)に戻ってください。 –

+0

'HashMap'は挿入命令を保持しないことに注意してください。最初のオブジェクトを取得することは、最初のユニークな文字ではありません。代わりに 'LinkedHashMap'を使用してください。 –

答えて

0

このコードでは、文字列sをchar配列に変換します。 char配列から1つのcharを取り出し、配列内の他のすべてのcharと比較します。それが見つからなければ(それ自身を除いて)ループを破り、それを印刷します。

public static void main(String[] args) { 

      String s = "abcd, afsfsfs, abcdef, 90> 20, abeds"; 
      char[] charArray = s.toCharArray(); 
      char current = 0; 
      for (int i = 0; i < charArray.length; i++) { 
       boolean contains = false; 
       current = charArray[i]; 
       int j = 0; 
       while (j < charArray.length) { 
        if (charArray[i] == charArray[j] && i != j) { 
         contains = true; 
         break; 
        } 
        j++; 
       } 
       System.out.println("current=" + current + " " + contains); 
       if (j == charArray.length && !contains) 
        break; 
      } 
      System.out.println(current); 
    } 

プリント:あなたはツール(IDE)を使用してください

current=a true 
current=b true 
current=c true 
current=d true 
current=, true 
current= true 
current=a true 
current=f true 
current=s true 
current=f true 
current=s true 
current=f true 
current=s true 
current=, true 
current= true 
current=a true 
current=b true 
current=c true 
current=d true 
current=e true 
current=f true 
current=, true 
current= true 
current=9 false 
9 
+0

回答の投稿のみが推奨されません。あなたが何を答えたのか、それをなぜそのようにしたのかを説明してください。 –

関連する問題