这道题主要使用了C++的几个API,大小写转化,字符串替换。其余的逻辑都比较简单。而且经查资料,string类字符串拼接的速度使用+=的速度是很快的。以下代码,也是用的+=来拼接字符串。

    string licenseKeyFormatting(string S, int K) {
        transform(S.begin(), S.end(), S.begin(), ::toupper);
        string oldStr = "-";
        string newStr = "";
        while (true) {
            string::size_type   pos(0);
            if ((pos = S.find(oldStr)) != string::npos)
            {
                S.replace(pos, oldStr.length(), newStr);
            }
            else
            {
                break;
            }
        }

        vector<string> V;
        int len = S.length();
        int firstPart = len % K;
        int Parts = len / K;
        if (Parts == 0)
        {
            return S;
        }
        V.push_back(S.substr(0, firstPart));
        if (firstPart != 0)
        {
            V.push_back("-");
        }
        for (int i = 0; i < Parts; i++)
        {
            V.push_back(S.substr(firstPart + i*K, K));
            if (i != Parts - 1)
            {
                V.push_back("-");
            }
        }

        string R;
        for (int i = 0; i < V.size(); i++)
        {
            R += V[i];
        }
        return R;
    }

 

posted on 2018-09-25 20:13  Sempron2800+  阅读(100)  评论(0编辑  收藏  举报