欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode 838. 推多米诺 题解

程序员文章站 2024-02-14 11:08:34
...

题目链接:https://leetcode-cn.com/problems/push-dominoes/
Leetcode 838. 推多米诺 题解
Leetcode 838. 推多米诺 题解
O(n)遍历两趟算受力,代码如下:

class Solution {
public:
    string pushDominoes(string dominoes) {
        int len = dominoes.size();
        int left[100005] = {0};
        int right[100005] = {0};

        int force = 0;
        for(int i = 0; i < len; i++) {
            if(dominoes[i] == 'R') {
                force = len;
            } else if(dominoes[i] == 'L') {
                force = 0;
            } else {
                force = max(force - 1, 0);
            }
            left[i] = force;
        }

        force = 0;
        for(int i = len - 1; i >= 0; i--) {
            if(dominoes[i] == 'L') {
                force = len;
            } else if(dominoes[i] == 'R') {
                force = 0;
            } else {
                force = max(force - 1, 0);
            }
            right[i] = force;
        }

        for(int i = 0; i < len; i++) {
            cout << left[i] << " ";
        }
        cout << endl;
        for(int i = 0; i < len; i++) {
            cout << right[i] << " ";
        }

        char s[len + 1];
        string res = "";
        for(int i = 0; i < len; i++) {
            if(left[i] == right[i]) {
                s[i] = '.';
            } else if(left[i] > right[i]) {
                s[i] = 'R';
            } else {
                s[i] = 'L';
            }
        }
        s[len] = '\0';
        return s;
    }
};
相关标签: Leetcode