[leetcode]838. Push Dominoes

[leetcode]838. Push Dominoes


Analysis

2019要开心鸭—— [每天刷题并不难0.0]

here are N dominoes in a line, and we place each domino vertically upright.
In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
[leetcode]838. Push Dominoes_第1张图片
After each second, each domino that is falling to the left pushes the adjacent domino on the left.
Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.
When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.
For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.
Given a string “S” representing the initial state. S[i] = ‘L’, if the i-th domino has been pushed to the left; S[i] = ‘R’, if the i-th domino has been pushed to the right; S[i] = ‘.’, if the i-th domino has not been pushed.
Return a string representing the final state.
[leetcode]838. Push Dominoes_第2张图片

Explanation:

讨论区的大神把这个问题分成了四种情况,然后就很简单了,进来仰望:
https://leetcode.com/problems/push-dominoes/discuss/132332/C%2B%2BJavaPython-Two-Pointers

Implement

class Solution {
public:
    string pushDominoes(string dominoes) {
        string d = 'L'+dominoes+'R';
        string res = "";
        int len = d.size();
        for(int i=0, j=1; j<len; j++){
            if(d[j] == '.')
                continue;
            int l = j-i-1;
            if(i>0)
                res += d[i];
            if(d[i] == d[j])
                res += string(l, d[i]);
            else if(d[i]=='L' && d[j]=='R')
                res += string(l, '.');
            else if(d[i]=='R' && d[j]=='L')
                res += string(l/2, 'R')+string(l%2, '.')+string(l/2, 'L');
            i = j;
        }
        return res;
    }
};

你可能感兴趣的:(LeetCode,Medium,intersting)