java程序返回仅使用字符串函数在字符串中出现3次以上的字符

时间:2018-01-07 06:05:32

标签: string function character

java程序返回仅使用字符串函数在字符串中出现3次以上的字符 仅使用charAt和length函数来获得解决方案

import java.util.*;
public class StringExample {
   public static void main(String args[]) {
       String str = "sofiiiffjjjh";
       Map < Character, Integer > charFreq = new HashMap < Character, Integer > ();
       if (str != null) {
           for (Character c: str.toCharArray()) {
               Integer count = charFreq.get(c);
               int newCount = (count == null ? 1 : count + 1);
               charFreq.put(c, newCount);
               if (newCount >= 3) {
                   System.out.println(c);
                }
           }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

此解决方案首先对输入字符串中的字符进行排序。它遍历字符串中的字符,将当前字符与前一个字符进行比较 1.如果它们相同,则递增计数 2.如果没有,它会检查previousChar发生的次数,如果超过3则打印并继续。

char [] strAsArray = s.toCharArray();
Arrays.sort(strAsArray);
String sorted = new String(strAsArray);
System.out.println(sorted);

if (sorted.length() > 0) {
    char previousChar = s.charAt(0);
    int count = 1;
    for (int i = 1; i < sorted.length(); i++) {
        if (sorted.charAt(i) == previousChar) {
            count++;
        } else {   // encountered new character
            if (count >= 3) {
                //if the previous character has appeared more than 3 times
                System.out.println(sorted.charAt(i - 1));
            }
            count = 1;
            previousChar = sorted.charAt(i);
        }
    }

    //To handle case where the String has only one character any number of times
    if (count >= 3) {
        System.out.println(sorted.charAt(sorted.length() - 1));
    }
}