LeetCode之Count Binary Substrings(Kotlin)

- 日理万妓 2022-03-16 14:14 203阅读 0赞

问题: 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.

Note: s.length will be between 1 and 50,000. s will only consist of “0” or “1” characters.


方法: 以0|1作为分界线,如00|11或者00|111,分界线前后0的长度和1的长度取min的值就是分界线前后的子串数,求所有分界线前后的子串数的和即为所有子串的个数。

具体实现:

  1. class CountBinarySubstrings {
  2. fun countBinarySubstrings(s: String): Int {
  3. var pre = s[0]
  4. var curLen = 0
  5. var preLen = 0
  6. var result = 0
  7. for (ch in s) {
  8. if (ch == pre) {
  9. curLen++
  10. } else {
  11. result += minOf(preLen, curLen)
  12. pre = ch
  13. preLen = curLen
  14. curLen = 1
  15. }
  16. }
  17. result += minOf(preLen, curLen)
  18. return result
  19. }
  20. }
  21. fun main(args: Array<String>) {
  22. val countBinarySubstrings = CountBinarySubstrings()
  23. val result = countBinarySubstrings.countBinarySubstrings("10101")
  24. println("result: " + result)
  25. }
  26. 复制代码

有问题随时沟通

具体代码实现可以参考Github

发表评论

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

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

相关阅读