838. Push Dominoes —— weekly contest 85
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'.'
1 class Solution {
2 public:
3 string pushDominoes(string dominoes) {
4 string res;
5 res = dominoes;
6 int n = dominoes.size();
7 for(int i = 0; i < n; i++){
8 if(dominoes[i] == '.'){
9 char left = '.';
10 char right = '.';
11 int j,k;
12 for(j = i - 1; j >= 0;j--){
13 if(dominoes[j]!='.'){
14 left = dominoes[j];
15 break;
16 }
17 }
18 for(k = i + 1; k < n; k++){
19 if(dominoes[k]!='.'){
20 right = dominoes[k];
21 break;
22 }
23 }
24 if(left=='R'&&right=='L'){
25 if(i-j!=k-i){
26 res[i] = i-j < k-i?left:right;
27 }
28 }else if(left == 'R'){
29 res[i] = left;
30 }else if(right == 'L'){
31 res[i] = right;
32 }
33
34 }
35 }
36 return res;
37 }
38 };
Another easier solution:
1 string pushDominoes(string d) {
2 d = 'L' + d + 'R';
3 string res = "";
4 for (int i = 0, j = 1; j < d.length(); ++j) {
5 if (d[j] == '.') continue;
6 int middle = j - i - 1;
7 if (i > 0) res += d[i];
8 if (d[i] == d[j]) res += string(middle, d[i]);
9 else if (d[i] == 'L' && d[j] == 'R') res += string(middle, '.');
10 else res += string(middle / 2, 'R') + string(middle % 2,'.') + string(middle / 2, 'L');
11 i = j;
12 }
13 return res;
14 }
最新文章
- Html_color code表示
- 继续node爬虫 — 百行代码自制自动AC机器人日解千题攻占HDOJ
- Run same command on all SQL Server databases without cursors
- gVim 配置方案 采用Vundle管理插件
- mybatis generator 使用
- asp.net资料! (.NET) (ASP.NET)
- Razor模板引擎
- linux下date命令实现时间戳与日期的转换
- 对比JQuery与JavaScript
- Present ViewController Modally
- python面向对象【进阶篇】
- data.table包简介
- mysql jdbc 官方编程示例
- LightGBM介绍及参数调优
- BZOJ4808马——二分图最大独立集
- hdu 5055
- code vs 2639 约会计划
- MathType编辑粗体空心字的技巧
- MongoDB(五)-- 副本集(replica Set)
- (object) array