LeetCode刷题笔记 5388. 重新格式化字符串 【字符串】

class Solution {
public:
    string reformat(string s) {
        string a, b;
        for (auto c : s)
        {
            if (isdigit(c)) a += c;
            if (isalpha(c)) b += c;
        }
        if (a.size() < b.size()) swap(a, b);
        if (a.size()-b.size() > 1) return "";
        string ret;
        for (int i = 0; i < a.size(); ++ i)
        {
            ret += a[i];
            if (i < b.size()) ret += b[i];
        }
        return ret;
    }
};

C++/C语言函数:isalpha()函数 isdigit(int c)宏

class Solution {
public:
    string reformat(string s) {
        string a, b, x;
        for(char c : s) if(isdigit(c)) a.push_back(c);
        else b.push_back(c);
        int m = min(a.size(), b.size());
        for(int i = 0; i < m; i += 1){
            x.push_back(a[i]);
            x.push_back(b[i]);
        }
        if(abs((int)a.size() - (int)b.size()) > 1) return "";
        if((int)a.size() == (int)b.size()) return x;
        if((int)a.size() > (int)b.size()) return x + a.back();
        return b.back() + x;
    }
};

重点: ( i n t ) a . s i z e ( ) (int)a.size()

猜你喜欢

转载自blog.csdn.net/g534441921/article/details/105613178