C++代码优化:判断字符串有效性的不同方法

本文将探讨如何判断一个字符串是否仅由'a'和'b'组成,并且所有'b'都在'a'之后。我们将提供两种不同的代码实现方式,并分析其优缺点。

方法一:使用范围for循环和栈cpp#include <bits/stdc++.h>using namespace std;

string isValid(const string& str) { stack strs; for (auto ch : str) { if (strs.empty()) { strs.push(ch); } else { if (strs.top() == 'a' && ch == 'b') { strs.pop(); } else { strs.push(ch); } } } if (strs.empty()) { return 'Yes'; } else { return 'No'; }}

int main() { // t 组数据 int t{}; cin >> t; while (t--) { string temp; cin >> temp; cout << isValid(temp) << endl; } return 0;}

代码解释:

  1. isValid函数接受一个字符串作为输入,并使用栈来判断字符串是否有效。2. 遍历字符串中的每个字符。3. 如果栈为空,则将字符压入栈中。4. 如果栈不为空,则检查栈顶元素是否为'a',当前字符是否为'b'。如果是,则将栈顶元素弹出,否则将当前字符压入栈中。5. 最后,如果栈为空,则说明字符串有效,否则无效。

方法二:使用for循环和三目运算符cpp#include #include #include

std::string isValid(const std::string& str) { std::stack strs; for (int i = 0; i < str.length(); i++) { char ch = str[i]; if (strs.empty()) { strs.push(ch); } else { if (strs.top() == 'a' && ch == 'b') { strs.pop(); } else { strs.push(ch); } } } return strs.empty() ? 'Yes' : 'No';}

int main() { // t 组数据 int t{}; std::cin >> t; while (t--) { std::string temp; std::cin >> temp; std::cout << isValid(temp) << std::endl; } return 0;}

代码解释:

  1. 与方法一类似,但使用普通的for循环遍历字符串。2. 使用三目运算符简化了返回语句。

总结

两种方法都能够有效判断字符串是否符合要求。方法一代码简洁易懂,方法二则更加高效。您可以根据实际情况选择适合您的方法。

C++代码优化:判断字符串有效性的不同方法

原文地址: https://www.cveoy.top/t/topic/x7F 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录