|
发表于 2023-10-10 21:22:48
|
显示全部楼层
这道题可以使用双指针来解决,时间复杂度为O(n)。
算法步骤如下:
1. 定义两个指针left和right,分别指向字符串s的开头和结尾。
2. 当left和right指向的字符都是'1'时,将right向右移动。
3. 当left和right指向的字符不全是'1'时,判断是否存在一个'0',如果存在则返回false,否则将left向右移动。
4. 重复步骤2和3,直到left和right相遇。
5. 如果没有返回false,则返回true。
C++代码如下:
- #include <iostream>
- #include <string>
- using namespace std;
- bool check(string s) {
- int left = 0, right = s.size() - 1;
- while (left < right) {
- while (s[left] == '1' && s[right] == '1') {
- right--;
- }
- if (s[left] != '1') {
- if (s.find('0', left) != string::npos && s.find('0', left) < right) {
- return false;
- }
- left++;
- }
- }
- return true;
- }
- int main() {
- string s;
- cin >> s;
- cout << (check(s) ? "true" : "false") << endl;
- return 0;
- }
复制代码
时间复杂度:O(n) |
|