819. Most Common Word

first:

class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {
        String[] words=paragraph.toLowerCase().split(" ");
        HashMap<String,Integer> wordsMap = new HashMap<String,Integer>();
        for(String s:words){
            s.trim();
            //s.toLowerCase();
            if(s.charAt(s.length()-1)=='!'||s.charAt(s.length()-1)=='?'||s.charAt(s.length()-1)=='\''||
                    s.charAt(s.length()-1)==','||s.charAt(s.length()-1)==';'||s.charAt(s.length()-1)=='.'){
                s=s.substring(0,s.length()-1);
            }
            if(!wordsMap.containsKey(s)){
                wordsMap.put(s,1);
            }else{
                wordsMap.put(s,wordsMap.get(s)+1);    
            }
        }
        
        int count=0;
        String returnWord = new String();
        HashSet<String> bannedSet = new HashSet<String>();
        for(String s:banned){
            bannedSet.add(s);
        }
        for(Map.Entry entry: wordsMap.entrySet()){
            if(!bannedSet.contains(entry.getKey())){
                int i=(Integer)entry.getValue();
                if(count < i){
                    count=(Integer)entry.getValue();
                    returnWord=(String)entry.getKey();
                }    
            }
        }  
        
        return returnWord;
    }
}

result:

Submission Detail

46 / 46 test cases passed.
Status:

Accepted

Runtime: 26 ms
Submitted: 0 minutes ago

Accepted Solutions Runtime Distribution

Sorry. We do not have enough accepted submissions to show runtime distribution chart.

conclusion:

猜你喜欢

转载自www.cnblogs.com/hzg1981/p/8966899.html