알고리즘/해커랭크

해커랭크 - CountingValleys

leeyuno 2020. 9. 14. 19:29
/*
 int steps: the number of steps on the hike
 string path: a string describing the path
 returns -> int: the number of valleys traversed
 해수면 아래에서 해수면까지 도달하면 계곡, 해수면 위에서 해수면까지 도달하면 산, 계곡이 몇개인지
 */

func countingValleys(steps: Int, path: String) -> Int {
    var result: Int = 0
    var valley: Int = 0

    path.map {
        if $0 == "D" {
            result -= 1
        } else if $0 == "U" {
            result += 1
            if result == 0 {
                valley += 1
            }
        }
    }

    return valley
}

countingValleys(steps: 12, path: "DDUUDDUDUUUD")