PS

Leetcode 2211. Count Collisions on a Road

Bryan Lee 2022. 4. 24. 22:51

문제 이해

- 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문이 아닌 삼항연산자를 사용할 수 있습니다.