개발/CodingTest
HackerRank - Counting Valley
Lumasca
2020. 6. 1. 09:07
// Complete the countingValleys function below.
static int countingValleys(int n, String s) {
int seaLevel = 0;//높이
int valley = 0;
boolean isValley = false;
for(int i = 0; i< n;i++){
char ch = s.charAt(i);
if(ch == 'U'){//올라가면 높이증가
seaLevel++;
}else if(ch == 'D'){//내려가면 높이 감소
seaLevel--;
}
if(seaLevel == 0){//높이가 0에 도달하면
if(isValley){//valley인 경우만 카운팅
valley++;
}
}else if(seaLevel > 0){//높이가 0보다 크면 valley가 아님
isValley = false;
}else if(seaLevel < 0){//높이가 0보다 작으면 valley
isValley = true;
}
}
return valley;
}