문제 이해
- directions 문자열에 나타난 문자에 따라 충돌 횟수를 구하라
해결 전략
- int i = 0 을 선언하고, directions 문자열을 순회하면서 L이 아닌 지점까지 이동합니다.
- 해당 지점부터 'R'이 발견되면, carsFromRight에 값을 하나씩 추가하고,
'S'가 발견되면 answer에 carsFromRight를,
'L'이 발견되면 answer에 carsFromRight+1을 더해줍니다.
- carsFromRight를 0으로 초기화한 후, 계속 순회합니다.
구현
class Solution {
public int countCollisions(String directions) {
int answer = 0;
int i = 0;
int carsFromRight = 0;
for( ; i<directions.length(); i++){
if(directions.charAt(i) != 'L'){
break;
}
}
for( ; i<directions.length(); i++){
if(directions.charAt(i) == 'R'){
carsFromRight++;
}else{
answer += (directions.charAt(i) == 'S') ? carsFromRight : carsFromRight+1;
carsFromRight = 0;
}
}
return answer;
}
}
피드백
- int i = 0 을 바깥에 선언하고, 두 개의 for문에서 동시에 활용할 수 있습니다.
- if-else문이 아닌 삼항연산자를 사용할 수 있습니다.
'PS' 카테고리의 다른 글
Leetcode 2207. Maximize Number of Subsequences in a String (0) | 2022.04.25 |
---|---|
Leetcode 2233. Maximum Product After K Increments (0) | 2022.04.24 |
Leetcode 83. Remove Duplicates from Sorted List (0) | 2022.04.24 |
자바(Java) 알고리즘 문제 풀이 - 결혼식 (1) | 2022.04.24 |
자바(Java) 알고리즘 문제 풀이 - 씨름선수 (0) | 2022.04.21 |