2011-11-14 976 views
1
for (int i = 0; i < s.length(); ++i) 
    { 
     if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') 
     { 
      ++array[s.charAt(i) - 'A']; 
     } 
    } 

我明白For循環。 s.length()是26,int [26]是精確的。所以這個循環將發生26次,0-25次。如果Char上的i,0-25在或者是AZ,那麼它將繼續到++array[s.charAt(i) - 'A'];從我看到它每個循環添加數組一次,或者在每個循環中爲數組添加數組的值,一會0秒會是2,因爲數組從0開始。所以在i -'A'的位置添加一個數組是我感到困惑的地方。++ array [s.charAt(i) - 'A']究竟幹什麼?

+1

我沒有得到烏爾問題 –

回答

8

語句++array[s.charAt(i) - 'A'];正在遞增由s.charAt(i) - 'A'索引的數組中的值。

此循環的作用是計算s中每個字母的出現次數。

- 'A'的原因是它「移動」了ASCII/Unicode值,因此A - Z的值爲0-25。因此更適合作爲數組索引。

5

array似乎是「反大寫字母」。通過從字符串中的任意字符減去字符'A',你得到的字母索引數組中:

'A' - 'A' == 0 
'B' - 'A' == 1 
'C' - 'A' == 2 

要理解這一點,你應該明白,是Java的對待char一樣(無符號)short。因此,你可以計算與char

+0

這使得它成爲了很多更清楚,這和上面的答案真的很有幫助。 – Renuz

1

數字符

(數字符不是一個歷史人物)

0
public class ArrayCharOccurence { 
    static final int ASCII = 256; 

    static char getMaxOccuringChar(String str) { 

     int count[] = new int[ASCII]; 

     int len = str.length(); 
     for (int i = 0; i < len; i++) 
      count[str.charAt(i)]++; 

     int max = -1; 
     char result = ' '; 

     for (int i = 0; i < len; i++) { 
      if (max < count[str.charAt(i)]) { 
       max = count[str.charAt(i)]; 
       result = str.charAt(i); 
      } 
     } 

     return result; 
    } 

    // Driver Method 
    public static void main(String[] args) { 
     String str = "sample string"; 
     System.out.println("Max occurring character is " 
       + getMaxOccuringChar(str)); 
    } 
}