编辑代码

/*
 * 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
    var sea_lvl = 0;
    var cnt = 0;
    for (var i = 0; i < steps; i++){
        if (path[i] == 'D'){
            sea_lvl -= 1;
        }
        else {
            sea_lvl += 1;
        }
        if (sea_lvl == 0 && path[i] == 'U'){
            cnt += 1;
        }
    }
    return cnt;
}

// test input

var steps = 8;
var path = ['U','D','D','D','U','D','U','U'];

console.log(countingValleys(steps, path));

// ans = 1