mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
新增1221.分割平衡字符串 JavaScript版本
This commit is contained in:
@ -108,6 +108,15 @@ public:
|
|||||||
## JavaScript
|
## JavaScript
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
var balancedStringSplit = function(s) {
|
||||||
|
let res = 0, total = 0;//res为平衡字符串数量 total为当前"R"字符和"L"字符的数量差
|
||||||
|
for(let c of s){// 遍历字符串每个字符
|
||||||
|
//因为开始字符数量差就是0,遍历的时候要先改变数量差,否则会影响结果数量
|
||||||
|
total += c === 'R' ? 1:-1;//遇到"R",total++;遇到"L",total--
|
||||||
|
if(total === 0) res++;//只要"R""L"数量一样就可以算是一个平衡字符串
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
Reference in New Issue
Block a user