Skip to content

Commit 995168e

Browse files
committed
solve no.657.There're 2 solutions.First one,use new Map().Second count horizontal(x),vertical(y).
1 parent db7b4fa commit 995168e

1 file changed

Lines changed: 55 additions & 3 deletions

File tree

javascript/index.js

Lines changed: 55 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1315,7 +1315,7 @@ var findAndReplacePattern = function(words, pattern) {
13151315
};
13161316
let word = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb";
13171317
// ["mee","aqq"]
1318-
console.log(findAndReplacePattern(word,pattern));
1318+
// console.log(findAndReplacePattern(word,pattern));
13191319

13201320
/**
13211321
* 657. Robot Return to Origin
@@ -1331,11 +1331,63 @@ var judgeCircle = function(moves) {
13311331
* x(0),y(0)
13321332
* u = d
13331333
* r = l
1334+
*
1335+
* 計算每個字母出現次數,r的出現次數 = l的出現次數; u 的出現次數 = d的出現次數
13341336
*/
1337+
// solution 1.
1338+
// TC:O(N)
1339+
// let direactionsCount = new Map();
1340+
// for(let i = 0;i < moves.length;++i) {
1341+
// direactionsCount.has(moves[i]) ? direactionsCount.set(moves[i],direactionsCount.get(moves[i])+1) : direactionsCount.set(moves[i],1);
1342+
// }
1343+
// // 取得Map.get(key)對應value
1344+
// if(direactionsCount.get("U") === direactionsCount.get("D") && direactionsCount.get("R") === direactionsCount.get("L")){
1345+
// return true;
1346+
// }
1347+
// return false;
1348+
1349+
// this solution?
1350+
// let direactionsObj = {};
1351+
// for(let i = 0;i < moves.length;++i) {
1352+
// if(Object.hasOwn(direactionsObj, moves[i])){
1353+
// direactionsObj[moves[i]] +=1;
1354+
// }else{
1355+
// direactionsObj[moves[i]] = 1;
1356+
// }
1357+
// }
1358+
// console.log(direactionsObj)
13351359

1360+
// solution 2.
1361+
// TC: O(N)
1362+
// 計算x和y各自出現次數
1363+
// x = 水平(左右); y = 垂直(上下)
1364+
let x = 0,y = 0;
1365+
// 水平(x):
1366+
// L:x--; R:x++;
1367+
// 垂直(y):
1368+
// U:y++ ; D: y--
1369+
for(let i = 0;i < moves.length;++i) {
1370+
if(moves[i] === 'R'){
1371+
x++;
1372+
}else if(moves[i] === 'U'){
1373+
y++;
1374+
}else if(moves[i] === 'L'){
1375+
x--
1376+
}else if(moves[i] === 'D'){
1377+
y--;
1378+
}
1379+
}
1380+
return x === 0 && y === 0;
13361381

13371382
};
13381383
let moves = "UD";
1339-
// Output: true
1340-
// Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
1384+
/*
1385+
Output: true
1386+
Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
1387+
*/
1388+
// let moves = "LL";
1389+
/*
1390+
Output: false
1391+
Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.
1392+
*/
13411393
console.log(judgeCircle(moves));

0 commit comments

Comments
 (0)