zentan66 / daily-coding

日常手写算法,编程题
0 stars 0 forks source link

【⭐️】LeetCode-分割平衡字符串 #36

Open zentan66 opened 3 years ago

zentan66 commented 3 years ago

在一个 平衡字符串 中,'L' 和 'R' 字符的数量是相同的。

给你一个平衡字符串 s,请你将它分割成尽可能多的平衡字符串。

注意:分割得到的每个字符串都必须是平衡字符串。

返回可以通过分割得到的平衡字符串的 最大数量 。

zentan66 commented 3 years ago

编码

var balancedStringSplit = function (s) {
  let num = 0,
    res = 0
  for (let i = 0, len = s.length; i < len; i++) {
    if (s.charAt(i) === 'L') {
      num++
    } else {
      num--
    }
    if (num === 0) {
      res++
    }
  }
  return res
}