LeetCode – 1221. Split a String in Balanced Strings

題目連結:

https://leetcode.com/problems/split-a-string-in-balanced-strings/

參考解法:

https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/573442/Swift

法ㄧ(自己的解法):

    func balancedStringSplit(_ s: String) -> Int {
        var rCount = 0
        var lCount = 0
        var result = 0
        for c in s {
        	if c == "R" {
        		rCount += 1
        	} else {
        		lCount += 1
        	}

        	if rCount != 0 && lCount != 0 && rCount == lCount { 
        		result += 1
      			rCount = 0
        		lCount = 0
        	}
        }
        return result
    }

法二(別人的解法):

    func balancedStringSplit(_ s: String) -> Int {
    	var sum = 0
    	var result = 0
    	for c in s {
    		if c == "R" {
    			sum += 1
    		} else {
    			sum -= 1
    		}

    		if sum == 0 {
    			result += 1
    		}
    	}
    	return result
    }