🔗 문제 링크

https://programmers.co.kr/learn/courses/30/lessons/67257


👨🏻‍💻 내가 작성한 코드

import java.util.*;
class Solution {
    public static long solution(String expression) {
        
    	// Expression을 숫자와 연산자를 따로 분리
        String express = expression.replaceAll("[*+-]"," ");
        System.out.println(express);
        
        ArrayList<Long> values = new ArrayList<>();
        for (int i: Arrays.stream(express.split(" ")).mapToInt(Integer::parseInt).toArray()){
        	values.add((long)i);
        }
        
        express = expression.replaceAll("[0-9]", "");
        ArrayList<Character> operators = new ArrayList<>();
        for (String i: express.split("")){
        	operators.add(i.charAt(0));
        }
        
        // 연산자의 우선순위 조합
        char[][] combination = {{'*','+','-'}, {'*','-','+'}, {'+','*','-'}, {'+','-','*'}, {'-','+','*'}, {'-','*','+'}};
        
        long max = -1;
        long result;

        for (char[] combi: combination) {
        	result = calculate(combi, values, operators);
        	if (result > max) max = result;
        	System.out.println(result);
        }
        
        return max;
    }
    
    public static long calculate(char[] operatorPriority, ArrayList<Long> values, ArrayList<Character> operators) {
        // values와 operators를 deep copy를 하며 복사본 생성
    	ArrayList<Long> valuesTemp = new ArrayList<>();
    	ArrayList<Character> operatorsTemp  = new ArrayList<>();;
		for (Long value: values) {
			valuesTemp.add(value);
		}
		for (char operator: operators) {
			operatorsTemp.add(operator);
		}
    	
    	int index = -1;
    	for (char c: operatorPriority) {
    		if (c =='*') {
    			while (operatorsTemp.contains('*')) {
    				index = operatorsTemp.indexOf('*'); 
    				valuesTemp.set(index, valuesTemp.get(index)*valuesTemp.get(index+1));
					valuesTemp.remove(index+1);
					operatorsTemp.remove(index);
    			}
    		}
    		else if (c == '+') {
    			while (operatorsTemp.contains('+')) {
    				index = operatorsTemp.indexOf('+'); 
    				valuesTemp.set(index, valuesTemp.get(index)+valuesTemp.get(index+1));
					valuesTemp.remove(index+1);
					operatorsTemp.remove(index);
    			}
    			
    		}
    		else if (c =='-') {
    			while (operatorsTemp.contains('-')) {
    				index = operatorsTemp.indexOf('-'); 
    				valuesTemp.set(index, valuesTemp.get(index)-valuesTemp.get(index+1));
					valuesTemp.remove(index+1);
					operatorsTemp.remove(index);
    			}
    		}
    	}
    	
    	return Math.abs(valuesTemp.remove(0));
    }
}


📝 결론

문제를 풀면서 시간이 많이 들고 헷갈렸던 내용은 크게 1) 문자열 쪼개기 2) DeepCopy에 관한 내용이었다.
1) 문자열 쪼개기 같은 경우는 "100-200*300-500+20"와 같은 문자열을 연산과 숫자를 따로 각각의 List에 넣는 작업이었다. 원래는 정규식을 사용해 바로 split을 하려고 하였으나 split에 여러 조건을 넣는것을 하지 못하여 결국 replace로 변경하고 돌아가는 방법을 택했다.
2) DeepCopy의 경우는 calculate method에서 values와 operators의 값들을 ArrayList valuesTemp=values;와 같은 방법으로 코드를 작성하였더니 반복문의 첫번째에는 잘 돌아갔으나 두번째 부터는 해당 values, operators의 값들이 전부 사라져있어서 indexoutofboundsexception이 발생하였다. 다음 문제를 풀 때는 Deep Copy/ Shallow Copy로 인해 발생하는 문제가 없도록 하자

Java의 collection에서는 shallow copy는 .copy()와 같은 method로 제공하지만 Deep Copy는 제공하지 않아 개발자가 List를 생성 후 직접 데이터를 복사해주는 방법으로 해야한다.

profile
블로그 이전했습니다. -> https://seongwon.dev/

0개의 댓글