DAY 4
0
Software Development

[One Punch 一拳搞定前後端面試] DAY-04 - 出現最多次

寫一個方法(函數)：題目給一個字串，請回傳該字串出現最多次的字元。

Example:

``````
ex1:

input: "abcccccde"
output: "c"

ex2:

input: "qwer33444kif66666"
output: "6"

``````

JS 解法

ex: "hi there"

``````obj = {
"h": 2,
"i": 1,
" ": 1,
"t": 1,
"e": 2,
"r": 1
}
``````

``````function maxChar(str) {

// key and value
let charMap = {}
for(let char of str){
if(!charMap[char]){
charMap[char] = 1
} else {
charMap[char] = charMap[char] + 1
}
}

// find the max value in the js Object
let maxCount = 0
let maxstr = ""
for(let k in charMap){
if(charMap[k] > maxCount){
maxCount = charMap[k];
maxstr = k
}
}

return maxstr;

}
``````

``````function maxChar2(str) {
let max = 0
let maxChar = ''
let charMap = {}

for (let c of str) {

charMap[c] = charMap[c] ? charMap[c] + 1 : 1

if (charMap[c] > max) {
max = charMap[c]
maxChar = c
}
}

return maxChar
}
``````

Java 解法

``````public class MaxString {

private String maxStr(String str) {

String ary[] = str.split("");

//put string into key and value
Map<String, Integer> count = new HashMap<String, Integer>();

for (String achar : ary) {
count.put(achar, count.getOrDefault(achar, 0) + 1);
}

System.out.println("String hashmap:" + count);

String maxKey = "";
int maxValue = 0;

for (Map.Entry<String, Integer> entry : count.entrySet()) {

if (entry.getValue() > maxValue) {
maxValue = entry.getValue();
maxKey = entry.getKey();
}
}
System.out.println("Max String is" + maxKey);

return maxKey;
}
``````