Balanced strings are those who have equal quantity of 'L' and 'R' characters.
Given a balanced string s
split it in the maximum amount of balanced strings.
Return the maximum amount of splitted balanced strings.
Example 1:
Input: s = "RLRRLLRLRL"
Output: 4
Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.
Example 2:
Input: s = "RLLLLRRRLR"
Output: 3
Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.
Example 3:
Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".
Example 4:
Input: s = "RLRRRLLRLL"
Output: 2
Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R'
Constraints:
1 <= s.length <= 1000
s[i] = 'L' or 'R'
balanced strings은 L과 R의 수가 같음을 의미한다.
balanced strings s
가 주어질때, 그것을 분할하여 얻을 수 있는 balanced strings의 최대 갯수를 구하시오.
// 처음엔 단순히 갯수를 세려다가,
// 밸런스라는게 결국 플러스 마이너스가 0이 되면 된다는 것을 알게 되었다.
func balancedStringSplit(s string) int {
balance := 0
amount := 0
characters := strings.Split(s, "")
for i := 0; i < len(characters); i++ {
if characters[i] == "L" {
balance++
} else {
balance--
}
if balance == 0 {
amount++
}
}
return amount
}
문자열에 그대로 인덱스를 붙일 수 있구나
func balancedStringSplit(s string) int {
var cnt, L, R int
for i:=0; i<len(s); i++{
if L==R{
cnt++
L=0
R=0
}
if s[i]=='L' {
L++
}else{
R++
}
}
return cnt
}
문자열을 그대로 for로 돌릴 수 있구나
go func balancedStringSplit(s string) int {
var counter, ls, rs int
for _, letter := range s {
if letter == 'L' {
ls++
} else if letter == 'R' {
rs++
}
if ls == rs {
counter++
}
}
return counter
}
코드작성법이 나보다 더 간결한 것 같다.
변수는 한 번에 선언하자.
func balancedStringSplit(s string) int {
balance, splits := 0, 0
for _, c := range s {
if string(c) == "L" {
balance -= 1
} else {
balance += 1
}
if balance == 0 {
splits += 1
}
}
return splits
}