您的位置:首页 > 其它

696. Count Binary Substrings

2020-01-14 09:32 169 查看

#696. Count Binary Substrings

Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0’s and 1’s, and all the 0’s and all the 1’s in these substrings are grouped consecutively.
Substrings that occur multiple times are counted the number of times they occur.

这道题的意思是,找出字符串中等个数的连续的0,1
这道题的思路是,判断前一个和当前是否一样,一样的话再看是不是小于之前的不同数字数量,是的话就+1。如果前一个和当前不一样,就把当前置为1。之前的数字数量置为前一个。

class Solution {
public int countBinarySubstrings(String s) {
int res = 0;
int prev = 0;
int cur = 1;
for(int i=1;i<s.length();i++) {
if(s.charAt(i) == s.charAt(i-1)) {
cur++;
}
else {
prev = cur;
cur = 1;
}

if(prev>=cur) {
res++;
}
}
return res;
}
}
  • 点赞
  • 收藏
  • 分享
  • 文章举报
onefanyf 发布了57 篇原创文章 · 获赞 0 · 访问量 187 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: