728x90
SMALL

using System;

public class Solution {
    public int solution(string s) {
        int answer = 0;
        string[] arr = s.Split(" "); // 빈 칸을 기준으로 나누기 {1} {2} {Z} {3}
        int index = 0;
        
        for(int i = 0; i < arr.Length; i++)
        {
            if(arr[i] == "Z")
            {
                if(index == 0)
                {
                    continue;
                }


                index--;
                answer -= int.Parse(arr[index]); // 바로 전에 더했던 수를 빼야한다.
            }
            else
            {
                answer += int.Parse(arr[i]);
                index = i + 1;
            }
        }
        return answer;
    }
}

 

/// continue 없어도 된다.

 

 

파이썬

////

 

def solution(s):
    arr = s.split(' ')
    result =[]
    for i in arr :
        if i=='Z':
            result.pop()
        else:
            result.append(int(i))
    return sum(result)

 

 

def solution(s):
    answer = 0
    for i in range(len(s := s.split(" "))):
        answer += int(s[i]) if s[i] != "Z" else -int(s[i-1])
    return answer

 

자바

 

import java.util.LinkedList;

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

        LinkedList<Integer> numbers = new LinkedList<>();

        if (!s.isEmpty()) 
        {
            String[] split_s = s.split(" ");

            for (int i = 0; i < split_s.length; i++) 
            {
                if (split_s[i].equals("Z")) 
                {
                    if (i - 1 >= 0 && numbers.size() > 0)
                        numbers.removeLast();
                }
                else
                    numbers.add(Integer.valueOf(split_s[i]));
            }
        }

        for (Integer number : numbers) 
        {
            answer += number;
        }

        return answer;
    }
}

 

 

import java.util.*;

class Solution {
    public int solution(String s) {
        int answer = 0;
        Stack<Integer> stack = new Stack<>();

        for (String w : s.split(" ")) 
        {
            if (w.equals("Z")) 
            {
                stack.pop();
            } 
            else 
            {
                stack.push(Integer.parseInt(w));
            }
        }
        
        for (int i : stack) 
        {
            answer += i;
        }
        
        return answer;
    }
}
728x90

설정

트랙백

댓글