2017-04-26 61 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

工具(IDE)你使用哪種?這取決於如何啓動調試器的工具。但是你也可以嘗試在程序的幾個地方添加測試輸出來檢查變量的值。另外,當結果應該是一個字符時,爲什麼該方法返回一個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數組中取出一個字符,並將其與所有其他字符進行比較。如果找不到它(除了它自己),則打破循環並打印它。這樣,你會發現第一個獨特的性格字符串:

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); 
    } 

打印:

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

只有回答帖子是不鼓勵的。請解釋你的回答以及你爲什麼選擇這樣做。 –

相關問題