728x90

https://school.programmers.co.kr/learn/courses/30/lessons/120853

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제)숫자와 "Z"가 공백으로 구분되어 담긴 문자열이 주어집니다. 문자열에 있는 숫자를 차례대로 더하려고 합니다. 이 때 "Z"가 나오면 바로 전에 더했던 숫자를 뺀다는 뜻입니다. 숫자와 "Z"로 이루어진 문자열 s가 주어질 때, 머쓱이가 구한 값을 return 하도록 solution 함수를 완성해보세요.

 

 

 

 

 

 

풀이)

class Solution {
    public int solution(String s) {
        int answer = 0;
        int sum = 0;
        int mus = 0;
        String t = s;

        if(s.indexOf("Z")==-1){
            s = s.replaceAll("\\s+", " ");
            String arr[] = s.split(" ");
            for(int i=0; i<arr.length; i++){
                answer+=Integer.parseInt(arr[i]);
            }
        }else{
            t = t.replaceAll("Z", "");
            t = t.replaceAll("\\s+", " ");
            System.out.println(t);
            String idx[] = t.split(" ");
            for(int i=0; i<idx.length; i++){
                sum+=Integer.parseInt(idx[i]);
            }

            String idxs[] = s.split(" ");
            for(int i=0; i<idxs.length; i++){
                if(idxs[i].equals("Z")){
                    mus += Integer.parseInt(idxs[i-1]);
                }
            }

            answer = sum -mus;

            
        }
        return answer;
    }
}

if()~else()문을 통해 문자열에 "Z"를 포함하고 있지 않다면, 그냥 문자만 더하고 그렇지 않다면 처리 할 수 있도록 설정해두었다.

728x90