An avid hiker keeps meticulous records of their hikes. During the last hike that took exactly steps steps, for every step it was noted if it was an uphill, U, or a downhill, D step. Hikes always start and end at sea level, and each step up or down represents a 1 unit change in altitude. We define the following terms:
一個狂熱的登山者保持他們的詳細紀錄。在最後一次登山的期間走了剛好 steps 步數,在每一個步數中,如果是上坡會紀錄 U,下坡會紀錄 D。 登山大部分開始和結束在海平面,每一個向上或向下都代表 1 的步數。我們定義如下:
– A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.
– A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.
Given the sequence of up and down steps during a hike, find and print the number of valleys walked through.
- 一座山是一系列連續的海拔高度,從海平面上升到海平面下降。 - 山谷是海平面以下的一系列連續步驟,從海平面下降開始,到海平面上升結束。 給與登山旅行中,上下台階的順序,找出並打印走過的山谷數量。
Example 1:
steps = 8, path = [DDUUUUDD] The hiker first enters a valley 2 units deep. Then they climb out and up onto a mountain 2 units high. Finally, the hiker returns to sea level and ends the hike.
solution:
先將 path 陣列中的上下坡進行切割成單一步數,並宣告 count 步數與 valley 山谷數量。
在遍歷迴圈的過程中,當水平線往下坡走時,則山谷數量 +1。
過程中的 count 步數會計算 上坡+1 與 下坡 -1,以確保回到水平位置時(count = 0),再次出現山谷的次數做累加。
Code 1: BigO(n)
'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', function(inputStdin) {
inputString += inputStdin;
});
process.stdin.on('end', function() {
inputString = inputString.split('\n');
main();
});
function readLine() {
return inputString[currentLine++];
}
/*
* Complete the 'countingValleys' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER steps
* 2. STRING path
*/
function countingValleys(steps, path) {
// Write your code here
let arrOfString = path.split("")
let count = 0,
valley = 0
for (let i = 0; i < steps; i++) {
if (count === 0 && arrOfString[i].toLowerCase() === "d") {
count -= 1
valley += 1
} else if (arrOfString[i].toLowerCase() === "d") {
count -= 1
} else {
count += 1
}
}
return valley;
}
function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const steps = parseInt(readLine().trim(), 10);
const path = readLine();
const result = countingValleys(steps, path);
ws.write(result + '\n');
ws.end();
}
FlowChart:
Example 1
steps = 8, path = [DDUUUUDD] step.1 i = 0, count = 0 path = D count -= 1 //count = -1 valley += 1 step.2 i = 1, count = -1 path = D count -= 1 //count = -2 step.3 i = 2, count = -2 path = U count += 1 //count = -1 step.4 i = 3, count = -1 path = U count += 1 //count = 0 step.5 i = 4, count = -1 path = U count += 1 //count = 1 step.6 i = 5, count = -1 path = U count += 1 //count = 2 step.7 i = 6, count = -1 path = D count -= 1 //count = 1 step.8 i = 7, count = -1 path = D count -= 1 //count = 0 return valley //1