LeetCode 838. Push Dominoes C++ [自己开发的博客网站,欢迎访问](www.weiboke.online) www.weiboke.online

自己开发的博客网站,欢迎访问 www.weiboke.online

838. Push Dominoes

There 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.

这里写图片描述

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.

Example 1:

Input: ".L.R...LR..L.."
Output: "LL.RR.LLRRLL.."

Example 2:

Input: "RR.L"
Output: "RR.L"
Explanation: The first domino expends no additional force on the second domino.

Note:

  • 0 <= N <= 10^5
  • String dominoes contains only ‘L’, ‘R’ and ‘.’

Approach

  1. 给你多诺米骨牌,告诉你每个多诺米骨牌倒向的位置,然后返回最终多诺米骨牌的状态。看到这道题会有点棘手好像也用不到什么思想或算法,我通常解决这类问题,比较喜欢分类讨论,抓住它的主要有哪几种情况,然后进行判断。所以我分了两种情况,一是遇到R ,这个牌是要向右倒,这里会有两种小情况:1.当前面没有L 了,那么我就可以一直向右倒,2.当前面有L,那么这里就要考虑它们会倒在一起。二是遇到L,此时这个牌要倒向左边,那么我让它倒,直至遇到非.为止,这两个是不会冲突的,因为我在处理R也会把最近的L一并处理,所以不会产生冲突。看代码之后思路会更加清晰。16ms

Code

class Solution {
public:
	string pushDominoes(string dominoes) {
		for (int i = 0; i < dominoes.size(); i++) {
			if (dominoes[i] == 'L') {
				for (int j = i-1; j >= 0; j--) {
					if (dominoes[j] == '.') {
						dominoes[j] = 'L';
					}
					else {
						break;
					}
				}
			}
			else if (dominoes[i] == 'R') {
				int Lindex = dominoes.find('L', i+1);
				if (Lindex == -1) {
					for (int j = i+1; j < dominoes.size(); j++) {
						dominoes[j] = 'R';
					}
					break;
				}
				else {
					int Rindex=0;
					for (int j = Lindex-1;; j--) {
						if (dominoes[j] == 'R') {
							Rindex = j;
							break;
						}
					}
					for (; i < Rindex; i++) {
						dominoes[i] = 'R';
					}
					int temp = Lindex;
					while (i < temp) {
						dominoes[i++] = 'R';
						dominoes[temp--] = 'L';
					}
					i = Lindex;
				}
			}
		}
		return dominoes;
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值