问题:获取String 中重复次数最多的字符,如果并列最多,返回任意一个。
代码如下:
测试类TestMain.java:
package com.test.string;
public class TestMain {
static String testString=”abdcdkfgasfhuiejk jfdsfhusdfhaeh jjk”;
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(“hello world”);
SearchMaxCharacterFromString TestString = new SearchMaxCharacterFromString();
Character c = TestString.getMaxChar(testString);
System.out.println(“MaxChar:” + c);
}
}
实现类SearchMaxCharacterFromString.java:
package com.test.string;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class SearchMaxCharacterFromString {
private Map<Character, Integer> mMap = new HashMap<Character, Integer>();
public SearchMaxCharacterFromString() {
}
public Character getMaxChar(String mStr) {
Character result = null;
try {
Merger(mStr);
result = getResult();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private void Merger(String s) throws NullPointerException {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (mMap.containsKey(c)) {
mMap.put(c, mMap.get(c) + 1);
} else {
mMap.put(c, 1);
}
}
}
private Character getResult() throws NullPointerException {
Entry<Character, Integer> tmp = null;
for (Entry<Character, Integer> entry : mMap.entrySet()) {
Integer value = entry.getValue();
System.out.println(value);
System.out.println(entry.getKey());
if (tmp == null || value > tmp.getValue()) {
tmp = entry;
}
}
return tmp.getKey();
}
}
请各位帮忙看一下,上面的代码有什么地方还需要改进的,请直言,另外,以前是做C语言开发的,代码中或多或少会有一些C的思想,有没有什么办法可以摒弃这种思想。
可以在生成map的时候做个简单的优化,在等到一个字符的出现次数大于字符长度的1/2时就可以直接返回字符了,具体修改getMaxChar 和Merger方法即可。
public Character getMaxChar(String mStr) {
Character result = null;
try {
result = Merger(mStr);
if (result == null) {
result = getResult1();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private Character Merger(String s) throws NullPointerException {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (mMap.containsKey(c)) {
mMap.put(c, mMap.get(c) + 1);
if (mMap.get(c) > s.length() / 2) {
return c;
}
} else {
mMap.put(c, 1);
}
}
return null;
}