解题思路
这是一个使用状态机的字符串处理问题。通过定义不同的状态来处理连续字符:
- 状态0:正常读取状态
- 状态1:状态
- 状态2:状态
关键点:
- 使用状态机处理字符串
- 跟踪上一个字符
- 根据状态决定是否保留当前字符
- 处理多组输入
算法步骤:
- 读取每个待校验字符串
- 使用状态机处理每个字符
- 根据状态转换规则更新状态
- 构建结果字符串
代码
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string fixSpelling(const string& str) {
if (str.empty()) return "";
string result;
result += str[0]; // 添加第一个字符
char last = str[0];
int state = 0; // 初始状态
for (int i = 1; i < str.length(); i++) {
char cur = str[i];
switch (state) {
case 0: // 正常读取状态
if (cur == last) {
state = 1; // 进入AA状态
} else {
state = 0;
}
break;
case 1: // AA状态
if (cur == last) {
continue; // AAA状态,跳过当前字符
} else {
state = 2; // 进入AAB状态
}
break;
case 2: // AAB状态
if (cur == last) {
continue; // AABB状态,跳过当前字符
} else {
state = 0;
}
break;
}
result += cur;
last = cur;
}
return result;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
Solution solution;
string str;
for (int i = 0; i < n; i++) {
cin >> str;
cout << solution.fixSpelling(str) << endl;
}
return 0;
}
import java.util.*;
class Solution {
public String fixSpelling(String str) {
if (str.isEmpty()) return "";
StringBuilder result = new StringBuilder();
result.append(str.charAt(0)); // 添加第一个字符
char last = str.charAt(0);
int state = 0; // 初始状态
for (int i = 1; i < str.length(); i++) {
char cur = str.charAt(i);
switch (state) {
case 0: // 正常读取状态
if (cur == last) {
state = 1; // 进入AA状态
} else {
state = 0;
}
break;
case 1: // AA状态
if (cur == last) {
continue; // AAA状态,跳过当前字符
} else {
state = 2; // 进入AAB状态
}
break;
case 2: // AAB状态
if (cur == last) {
continue; // AABB状态,跳过当前字符
} else {
state = 0;
}
break;
}
result.append(cur);
last = cur;
}
return result.toString();
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Solution solution = new Solution();
for (int i = 0; i < n; i++) {
String str = sc.next();
System.out.println(solution.fixSpelling(str));
}
sc.close();
}
}
class Solution:
def fix_spelling(self, s: str) -> str:
if not s:
return ""
result = [s[0]] # 添加第一个字符
last = s[0]
state = 0 # 初始状态
for i in range(1, len(s)):
cur = s[i]
if state == 0: # 正常读取状态
if cur == last:
state = 1 # 进入AA状态
else:
state = 0
elif state == 1: # AA状态
if cur == last:
continue # AAA状态,跳过当前字符
else:
state = 2 # 进入AAB状态
elif state == 2: # AAB状态
if cur == last:
continue # AABB状态,跳过当前字符
else:
state = 0
result.append(cur)
last = cur
return ''.join(result)
def main():
n = int(input())
solution = Solution()
for _ in range(n):
s = input()
print(solution.fix_spelling(s))
if __name__ == "__main__":
main()
算法及复杂度
- 算法:状态机
- 时间复杂度:,其中 是字符串长度
- 空间复杂度:,用于存储结果字符串