字串中統計某字母的次數等【Java Base】

來源:互聯網
上載者:User

【題目】給你一個字串,包含了空格等標點符號,要你計算出出現次數最多的字母和該字母出現的次數。
【code】:
private static void totalTimes(String str) {
char[] ch = str.toCharArray();
Map<Character, Integer> timesMap = new HashMap<Character,
Integer>();

for (int i = 0; i < ch.length; i++) {
if ((ch[i] >= 65 && ch[i] <= 90) || (ch[i] >= 97
&& ch[i] <= 122)) {
Integer freq = timesMap.get(ch[i]);
timesMap.put(ch[i], freq == null ? Integer.valueOf(1) : ++freq);
}
}

int charMaxIndex = Collections.max(timesMap.values());
int charMinIndex = Collections.min(timesMap.values());

Set<Character> maxSet = new HashSet<Character>();
Set<Character> minSet = new HashSet<Character>();

for(Map.Entry<Character, Integer> entry : timesMap.entrySet()){

if(entry.getValue().equals(charMaxIndex)){
maxSet.add(entry.getKey());
}

if(entry.getValue().equals(charMinIndex)){
minSet.add(entry.getKey());
}

}

System.out.println("出現最多的字母:" + maxSet);
System.out.println("出現次數:" + charMaxIndex);
System.out.println("出現最小的字母:" + minSet);
System.out.println("出現次數:" + charMinIndex);

}
當然,除了以上,每個人都會有自己心中的code,呵呵!如果不能利用到Java裡的集合,那麼就可能在數組上做文章了,如下:

  1. String str = 
    "hello wolrd wlllkdsfhksadfls?sdfls sdf.pqyutgvAAAxzsdfs "
     +  
  2.                "lsdfj,ljsfd  ajfdsak sfksjdfisfsdkfj lsdfjsidf jsafdalsjfs sfskdfjs"
    ;  
  3.        int
    [] strCounts = 
    new
     
    int
    [
    255
    ];  
  4.        int
     biggestCount = 
    0
    ;  
  5.        char
     biggestCh = 
    0
    ;  
  6.        char
     ch = 
    0
    ;  
  7.        int
     currentCount = 
    0
    ;  
  8.        for
     (
    int
     i = str.length() - 
    1
    ; i >= 
    0
    ; i--) {  
  9.            ch = str.charAt(i);  
  10.            currentCount = ++strCounts[ch];  
  11.            if
     (currentCount > biggestCount) {  
  12.                biggestCount = currentCount;  
  13.                biggestCh = ch;  
  14.            }  
  15.        }  
  16.        System.out.println(biggestCh);  
  17.        System.out.println(biggestCount); 
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.