【LeetCode】1417. Reformat strings

topic

You are given a string s that is a mixture of numbers and letters, where the letters are all lowercase English letters.
Please reformat the string so that any two adjacent characters have different types. That is, letters should be followed by numbers, and numbers should be followed by letters.
Please return the reformatted string; if it cannot be reformatted as required, return an empty string.

Example 1:

Input: s = "a0b1c2"
Output: "0a1b2c"
Explanation: The types of any two adjacent characters in "0a1b2c" are different. "a0b1c2", "0a1b2c", "0c2a1b" are also answers that meet the requirements of the question.

Example 2:

Input: s = "leetcode"
Output: ""
Explanation: "leetcode" contains only letters, so the reformatting condition cannot be met.

Example 3:

Input: s = "1229857369"
Output: ""
Explanation: "1229857369" contains only numbers, so the reformatting condition cannot be met.

Example 4:

Input: s = "covid2019"
Output: "c2o0v1i9d"

Example 5:

Input: s = "ab123"
Output: "1a2b3"

hint:

1 <= s.length <= 500
s consists of lowercase English letters and/or numbers only.

answer

Use queue

class Solution {
    
    
public:
    string reformat(string s) {
    
    
        queue<char> shuzi,zimu;
        string res = "";
        for(char c:s)
        {
    
    
            if(c>='0' && c<='9')
                shuzi.push(c);
            else
                zimu.push(c);
        }

        int shuzi_cnt = shuzi.size();
        int zimu_cnt = zimu.size();

        if(abs(shuzi_cnt-zimu_cnt)>=2)
            return "";
        else if(shuzi_cnt >= zimu_cnt)
        {
    
    
            while(!shuzi.empty())
            {
    
    
                res += shuzi.front();
                shuzi.pop();
                if(!zimu.empty())
                {
    
    
                    res += zimu.front();
                    zimu.pop();
                }
            }
        }
        else
        {
    
    
            while(!zimu.empty())
            {
    
    
                res += zimu.front();
                zimu.pop();
                if(!shuzi.empty())
                {
    
    
                    res += shuzi.front();
                    shuzi.pop();
                }
            }
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/qq_45972928/article/details/126294336