1 条题解

  • 0
    @ 2022-11-2 16:11:50

    直接计数

    O(s)O(|s|)

    #include <bits/stdc++.h>
    using namespace std;
    string s;
    int cnt[26][26];
    int main()
    {
        cin >> s;
        int maxCnt = 0;
        for (int i = 0; i < s.length() - 1; i++)
        {
            cnt[s[i] - 'a'][s[i + 1] - 'a']++;
            maxCnt = max(maxCnt, cnt[s[i] - 'a'][s[i + 1] - 'a']);
        }
        for (int i = 0; i < 26; i++)
            for (int j = 0; j < 26; j++)
                if (cnt[i][j] == maxCnt)
                    cout << (char)(i + 'a') << (char)(j + 'a') << "\n";
        return 0;
    }
    

    STL map

    #include <bits/stdc++.h>
    using namespace std;
    string s;
    // m[str] 统计 str 的出现次数
    map<string, int> m;
    int main()
    {
        cin >> s;
        int maxCnt = 0;
        for (int i = 0; i < s.length() - 1; i++)
        {
            m[s.substr(i, 2)]++;
            maxCnt = max(maxCnt, m[s.substr(i, 2)]);
        }
        //可以这样写
        for (map<string, int>::iterator it = m.begin(); it != m.end(); it++)
            if ((*it).second == maxCnt)
                cout << (*it).first << "\n";
    
        //也可以这样写
        for (auto it = m.begin(); it != m.end(); it++)
            if (it->second == maxCnt)
                cout << it->first << "\n";
    
        //还可以这样写
        for (auto it : m)
            if (it.second == maxCnt)
                cout << it.first << "\n";
        
        return 0;
    }
    
    • 1

    信息

    ID
    1120
    时间
    1000ms
    内存
    256MiB
    难度
    3
    标签
    递交数
    85
    已通过
    43
    上传者