LEETCODE算法:5388. Reformat The String

题目

Given alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).

You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.

Return the reformatted string or return an empty string if it is impossible to reformat the string.

Example 1:

Input: s = "a0b1c2" Output: "0a1b2c" Explanation: "0a1b2c" doesn't have any letter followed by digit or any digit followed by character. "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations. Example 2:

Input: s = "leetcode" Output: "" Explanation: "leetcode" has only characters so we cannot separate them by digits. Example 3:

Input: s = "1229857369" Output: "" Explanation: "1229857369" has only digits so we cannot separate them by characters. Example 4:

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

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

Constraints:

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

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//把数字和字母分离出来,然后再逐一加入新的字符串
class Solution {
public:
string reformat(string s) {
vector<char> t1;
vector<char> t2;
string ans;
for (int i = 0; i < s.length(); i++)
{
if (s[i] >= '0' && s[i] <= '9') {
t2.push_back(s[i]);
}
else {
t1.push_back(s[i]);
}
}
int tmp = t1.size() - t2.size();
if (tmp == 0 || tmp == 1 ) {
auto t1b = t1.begin();
auto t2b = t2.begin();
while (t1b != t1.end() && t2b != t2.end())
{
ans+=*t1b;
ans +=*t2b;
t1b++;
t2b++;
}
if (t1b != t1.end()) ans += *t1b;
if(t2b!=t2.end()) ans+=*t2b;
return ans;
}
else if (tmp == -1) {
auto t1b = t1.begin();
auto t2b = t2.begin();
while (t1b != t1.end() && t2b != t2.end())
{
ans+=*t2b;
ans +=*t1b;
t1b++;
t2b++;
}
if (t1b != t1.end()) ans += *t1b;
if(t2b!=t2.end()) ans+=*t2b;
return ans;
}
else {
return "";
}
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//排名第一大佬的代码,一样的功能逻辑更简洁的代码
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;
}
};