给你一个二进制字符串 s ,该字符串 不含前导零 。
如果 s 最多包含 一个由连续的 ‘1’ 组成的字段 ,返回 true 。否则,返回 false 。
示例 1:
输入:s = "1001"
输出:false
解释:字符串中的 1 没有形成一个连续字段。
示例 2:
输入:s = "110"
输出:true
提示:
1 <= s.length <= 100
s[i] 为 '0' 或 '1'
s[0] 为 '1'
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法一,最笨的方式,这种没有完全利用题目种给的一些条件,导致处理起来比较麻烦。
bool checkOnesSegment(char * s){
int len = strlen(s);
int i = 0, j = 0;
int cnt = 0;
if ((len == 1 && s[0] == '1') ||\
(len == 2) &&(s[0] == '1') &&(s[1] == '1'))
{
return true;
}
for (int i = 0; i < len; i++) {
printf("i:%d s[i]:%c\n", i, s[i]);
if (s[i] == '1') {
j = i;
printf(" j:%d s[j]:%c\n", j, s[j]);
while (s[j] == '1') {
if (j == len - 1) {
goto check;
}
j++;
}
check:
printf(" j:%d s[j]:%c\n", j, s[j]);
cnt += 1;
i = j;
printf(" cnt:%d\n", cnt);
if (cnt == 2) {
return false;
}
}
}
if (cnt == 1) {
return true;
}
else {
return false;
}
}
方法二,题目中给了一个很有用的条件该字符串 不含前导零
,充分利用这个条件可以简化算法实现;
bool checkOnesSegment(char * s){
bool res = true;
int len = strlen(s);
for(int i = 1;i < len; i++) {
if (s[i] == '1' && s[i - 1] == '0') {
res = false;
}
}
return res;
}