⬆︎
×

[PAT-A] 1071 Speech Patterns

Java

测试点2、3超时

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        String s = reader.readLine();

        Map<String, Integer> words = new HashMap<>();

        for (int i = 0; i < s.length(); ++i) {
            if (Character.isLetterOrDigit(s.charAt(i))) {
                StringBuilder word = new StringBuilder();
                int j = i;
                while (j < s.length() && Character.isLetterOrDigit(s.charAt(j))) {
                    char ch = s.charAt(j);
                    if (Character.isUpperCase(ch)) {
                        ch = Character.toLowerCase(ch);
                    }
                    word.append(ch);
                    ++j;
                }
                String wordStr = word.toString();
                words.put(wordStr, words.getOrDefault(wordStr, 0) + 1);
                i = j;
            }
        }

        String maxWord = "";
        int cnt = 0;
        for (Map.Entry<String, Integer> entry : words.entrySet()) {
            if (entry.getValue() > cnt) {
                maxWord = entry.getKey();
                cnt = entry.getValue();
            }
        }

        System.out.println(maxWord + " " + cnt);
    }
}

C++

#include <iostream>
#include <cstring>
#include <algorithm>
#include <map>

using namespace std;

const int MAXN = 10010, INF = 1e7 + 10;

string s;
map<string, int> words;

int main() {
    getline(cin, s);

    for (int i = 0; i < s.size(); ++i) {
        if (isalnum(s[i])) {
            string word;
            int j = i;
            while (j < s.size() && isalnum(s[j])) {
                if (isupper(s[j])) s[j] = tolower(s[j]);
                word += s[j];
                ++j;
            }
            words[word]++;
            i = j;
        }
    }

    string max_word;
    int cnt = 0;
    for (auto word: words)
        if (word.second > cnt) {
            max_word = word.first;
            cnt = word.second;
        }

    cout << max_word << " " << cnt << endl;
    return 0;
}

发表评论