← 返回 microsoft 的题目列表Count Swaps
类型:online_judge
There are N balls positioned in a row. Each of them is either red or white. In one move we can swap two adjacent balls. We want to arrange all the red balls into a consistent segment. What is the minimum number of swaps needed?
Write a function:
def solution(S):
that, given string S of length N built from characters 'R' and 'W', representing red and white balls respectively, returns the minimum number of swaps needed to arrange all the red balls into a consistent segment. If the result exceeds 10^9, return -1.
Examples:
Given S = "WRRWWR", the function should return 2.
Given S = "WWRWWWWRWR", the function should return 4.
Given S = "WWW", the function should return 0.
Given S = "RW" * 100000, the function should return -1.
Constraints:
N is an integer within the range [1..200,000].
String S is made only of the characters 'R' and/or 'W'.
Example
Input
WRRWWR