LeetCode696. 计数二进制子串

末蓝、 2022-05-20 07:24 320阅读 0赞

给定一个字符串 s,计算具有相同数量0和1的非空(连续)子字符串的数量,并且这些子字符串中的所有0和所有1都是组合在一起的。

重复出现的子串要计算它们出现的次数。

示例 1 :

  1. 输入: "00110011"
  2. 输出: 6
  3. 解释: 6个子串具有相同数量的连续10:“0011”,“01”,“1100”,“10”,“0011 01”。
  4. 请注意,一些重复出现的子串要计算它们出现的次数。
  5. 另外,“00110011”不是有效的子串,因为所有的0(和1)没有组合在一起。

示例 2 :

  1. 输入: "10101"
  2. 输出: 4
  3. 解释: 4个子串:“10”,“01”,“10”,“01”,它们具有相同数量的连续10

注意:

  • s.length 在1到50,000之间。
  • s 只包含“0”或“1”字符。

思路:首先想到暴力解法,两层循环找出s的所有子串进行判断,结果跟预料的差不多,会超出时间限制。

解法一:(超出时间限制)

  1. class Solution {
  2. public int countBinarySubstrings(String s) {
  3. if(s==null||s.length()==0) {
  4. return 0;
  5. }
  6. int count=0;
  7. for(int i=0;i<s.length();i++) {
  8. for(int j=i+1;j<=s.length();j++) {
  9. String tempS=s.substring(i, j);
  10. // System.out.println(tempS);
  11. if(isTrue(tempS)) {
  12. count++;
  13. }
  14. }
  15. }
  16. return count;
  17. }
  18. //判断s是否0,1组合且数量相同,0与0组合,1与1组合
  19. public static boolean isTrue(String s) {
  20. int len=s.length();
  21. if(len%2!=0) {
  22. return false;
  23. }
  24. if(s.charAt(0)==s.charAt(len-1)) {
  25. return false;
  26. }
  27. for(int i=0;i<len/2-1;i++) {
  28. if(s.charAt(i)!=s.charAt(i+1)) {
  29. return false;
  30. }
  31. }
  32. for(int i=len/2;i<len-1;i++) {
  33. if(s.charAt(i)!=s.charAt(i+1)) {
  34. return false;
  35. }
  36. }
  37. // System.out.println(s);
  38. return true;
  39. }
  40. }

解法二:将连续的0,1个数存入数组中,遍历数组取两两之间最小的个数求和。

  1. class Solution {
  2. public int countBinarySubstrings(String s) {
  3. if(s==null||s.length()<=1) {
  4. return 0;
  5. }
  6. int count=0;
  7. int a[]=new int[s.length()]; //用来存储连续0,1的个数
  8. char ch[]=s.toCharArray();
  9. int temp=0; //连续0,1的长度
  10. for(int i=0;i<s.length()-1;i++) {
  11. a[temp]++;
  12. if(ch[i]!=ch[i+1]) {
  13. temp++;
  14. }
  15. }
  16. a[temp]++;
  17. for(int i=0;i<temp;i++) {
  18. count+=Math.min(a[i], a[i+1]);
  19. }
  20. return count;
  21. }
  22. }

发表评论

表情:
评论列表 (有 0 条评论,320人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LeetCode 647】回文

    题目描述 给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。 具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。 示例 1:

    相关 LeetCode696. 计数二进制

    给定一个字符串 `s`,计算具有相同数量0和1的非空(连续)子字符串的数量,并且这些子字符串中的所有0和所有1都是组合在一起的。 重复出现的子串要计算它们出现的次数。 示例