본문 바로가기

Algorithm/프로그래머스

[프로그래머스/Java]가장 가까운 같은 글자, 두 개 뽑아서 더하기

728x90
반응형

어떻게 풀까 생각하다가 이중 for문으로 쉽게 풀 수 있겠다 생각이 들었다.

public class cote35 {
	public static void main(String[] args) {
    	String s = "banana";
        char[] ch = s.toCharArray();
        int[] result = new int[ch.length];
        result[0] = -1;
        //int 배열을 결과로 생성하고 인덱스 0번째는 무조건 -1이니까 미리 넣어준다.
        //0인덱스를 미리 넣었으니 1부터 시작
        for(int i=1; i<ch.length; i++) {
        	for(int y=1; y<=i; y++) {
            	if(ch[i]==ch[i-y]) {
                	result[i] = y;
                    break;
                } else {
                	result[i] = -1;
                }
            }
        }
        System.out.println(Arrays.toString(result));

다른 사람의 풀이를 보니 메서드를 사용한 코드를 보았다.

class Solution35 {
	public int[] solution(String s) {
    	Map<Character, Integer> map = new HashMap<>();
        for(int i=0; i<s.length(); i++) {
        	char ch = s.charAt(i);
            result[i] = i - map.getOrDefault(ch, i + 1);
            //map에서 현재 문자 ch에 대한 마지막 위치를 가져온다.
            //만약 이전에 문자가 없다면 기본값으로 i+1을 반환한다.
            //반환 값을 현재 위치에서 빼주고 차이를 구한다.
            map.put(ch, i);
        }
        return result;
    }
    //스트림으로 다른 사람이 푼 코드
    public int[] solution1(String s) {
    	return IntStream.range(0, s.length())
        .map(i -> s.substring(0, i).lastIndexOf(s.charAt(i)) > -1 ?
        i - s.substring(0, i).lastIndexOf(s.charAt(i)) : -1).toArray();
        //같은 문장이 반복되는 것 같아서 다른 방식으로 해보기
        return IntStream.range(0, s.length())
        .map(i -> {
            char currentChar = s.charAt(i);
            int lastIndex = map.containsKey(currentChar) ? map.get(currentChar) : -1;
            map.put(currentChar, i);
            return lastIndex > -1 ? i - lastIndex : -1;
        })
        .toArray();
    }
}

이 문제를 보자마자 Set이 떠올랐다.

public class cote36 {
	public static void main(String[] args) {
    	int[] number = {2,1,3,4,1};
        Arrays.sort(number);
        Set<Integer> set = new HashSet<>();
        for(int i=0; i<number.length; i++) {
        	for(int y=i+1; i<number.length; y++) {
            	set.add(number[i] + number[y]);
            }
        }
        int[] result = new int[set.size()];
        int index = 0;
        
        for(Integer value : set) {
        	result[index++] = value;
        }
        System.out.println(Arrays.toString(result));
        //이렇게 문제를 풀었을 때 보기에 나와있는 테스트 케이스는 통과했지만
        //몇몇 테스트 케이스에 오류가 나서 바꿔보았다.
	}
}
class Solution36 {
	public List<Integer> solution(int[] numbers) {
    	boolean[] sumResult = new boolean[201];
        //조건을 보고 길이를 정해버림.
        for(int i=0; i<numbers.length; i++_ {
        	for(int j=i+1; j<numbers.length; j++) {
            	sumResult[numbers[i] + numbers[j]] = true;
            }
        }
        List<Integer> resultList = new ArrayList<>();
        for(int i=0; i<sumResult.length; i++) {
        	if(sumResult[i]) {
            	resultList.add(i);
            }
        }
        return resultList;
    }
    //false, false, true, true, true, true, true, true, false
    //위와 같이 결과같에 대한 인덱스에만 true 값이 들어가기 때문에 if문에 참값인 인덱스 번호를 뽑으면 됌.

 

728x90
반응형