LeetCode:1221 Split a String in Balanced Strings

題目:
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:
Input: s = “RLRRLLRLRL”
Output: 4
Explanation: s can be split into “RL”, “RRLL”, “RL”, “RL”, each substring contains same number of ‘L’ and ‘R’.

這題Golang跟其它語言不太一樣的是
string跟rune的差別
在string[index]中這樣取值
取出來的是byte(uint8)
由於取出的是位元組
所以要將string轉換成rune
可以參考:https://openhome.cc/Gossip/Go/String.html

解法:

func balancedStringSplit(s string) int {    balance := 0    reslut :=0    for _, temp := range(s){        if string(temp)=="L"{            balance += 1        } else {            balance -= 1        }        if balance==0 {            reslut += 1        }    }    return reslut}

沒有留言:

張貼留言

About

努力在程式的大海
用力的揮動雙手
找出屬於自己的航線

Blog Archive

Traffic