알고리즘 풀이 방법입니다.
문제(Problem) -> 생각(Think) -> 해결책(Solution) -> 리뷰(Review) 를 통해서 정리해서 작성합니다.
Problem📄

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

 

프로그래머스

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

programmers.co.kr


Think🤔

문제에 대한 이해를 잘못함

처음 문자 "banana" 이면

"banana" 처럼 고정돼서 b가 아닌 값을 만나면 ba 부분을 1개 세어주고 다시 n을 만나서 1개 세어주는걸로 이해


Solution✍
class CodeRunner{
	public static void main(String[] args){
        String s = "aaabbaccccabba";
        
        int answer = 0;
        int ocnt = 0;
        int xcnt = 0;
        char x = s.charAt(0);
        boolean xSwitch = false;
        
        for(int i=0; i<s.length(); i++){
            //System.out.println(" x : " + x + ", xcnt : " + xcnt + ", ocnt : " + ocnt + "  , s.char(I) : " + s.charAt(i));
            if(xSwitch){
                x = s.charAt(i);
                xSwitch = false;
                continue;
            }else if(s.charAt(i) == x){
                xcnt++;
            }else{
                ocnt++;
            }
            
            if(xcnt == ocnt){
                answer++;
                xcnt=1;
                ocnt=0;
                xSwitch = true;
            }
        }
        
        if(!xSwitch){answer++;}
        
        System.out.println("answer : " + answer);
	}
}

마지막에 abracadabra 처럼 a가 혼자 남게될 경우를 안세어주어서 스위치문을 이용해서 체크를 했다.

 

xcnt는 첫글자를 계속해서 바꿔주는 변수를 세어주는 변수

ocnt는 첫글자를 제외한 변수를 세어주는 변수

를 이용해서 이 길이가 같게되면 숫자를 더 해주는 방식으로 풀이


Review🤩

 

알고리즘 풀이 방법입니다.
문제(Problem) -> 생각(Think) -> 해결책(Solution) -> 리뷰(Review) 를 통해서 정리해서 작성합니다.
Problem📄

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

 

프로그래머스

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

programmers.co.kr


Think🤔
import java.lang.Math;

class Solution {
    public String solution(String X, String Y) {
        // x , y 랑 둘 중 작은거로 반복문 돌림
        // 작은거를 내림차순으로 정렬 그거 리턴
        // 내림차순으로 정렬했을때 제일 큰 수 0일 경우 0으로 리턴
        // 같은 수 없을 경우 -1
        String answer = "";
        X = change(X);
        Y = change(Y);

        if(X.charAt(0) == '0' || Y.charAt(0) == '0'){return "0";}
        
        String big = (X.length() >= Y.length() ? X : Y);
        String small = (X.length() >= Y.length() ? Y : X);

        char tmp = ' ';
        for(int i=0; i<small.length(); i++){
            if(big.indexOf(small.charAt(i)) != -1){
                answer+=small.charAt(i);
                big = big.substring(0, big.indexOf(small.charAt(i))) + big.indexOf(big.indexOf(small.charAt(i)), big.length() -1);
            }
        }
        
        if(answer.length() == 0){
            answer = "-1";
        }
        
        return answer;
    }
    
    public String change(String str){
        char[] ch = str.toCharArray();
        char temp = ' ';
        
        for(int i=0; i<str.length(); i++){
            for(int j=i+1; j<str.length()-1; j++){
                if(ch[i] < ch[j]){
                    temp = ch[i];
                    ch[i] = ch[j];
                    ch[j] = temp;
                }
            }
        }
        
        str = new String(ch, 0, ch.length);
        return str;
    }
}

change를 이용해서 내림차순으로 배치한 후

같은게 있으면 제거하고 answer++ 하는 방식으로 했으나 틀림..


Solution✍
class Solution {
    public String solution(String X, String Y) {
        // String으로 하면 시간 초과
        StringBuilder answer = new StringBuilder();
        
        int[] xArr = new int[10];
        int[] yArr = new int[10];
        
        for(String tmp : X.split("")){
            xArr[Integer.parseInt(tmp)]++;
        }
        
        for(String tmp : Y.split("")){
            yArr[Integer.parseInt(tmp)]++;
        }
        
        for(int i=9; i>=0; i--){
            if(xArr[i] > 0 && yArr[i] > 0){
                for(int j=0; j<Math.min(xArr[i],yArr[i]); j++){
                    answer.append(i);
                }
            }
        }
        
        if(answer.length() == 0){return "-1";}
        else if(answer.charAt(0) == '0'){return "0";}
        
        return answer.toString();
    }
}

Review🤩

동적인 문자열을 다룰때 StringBuilder를 사용하는것이 효과적 String으로 해서 통과하지 못함

배열 길이 이용해서 구하므로 내림차순을 할 필요 없음


 

알고리즘 풀이 방법입니다.
문제(Problem) -> 생각(Think) -> 해결책(Solution) -> 리뷰(Review) 를 통해서 정리해서 작성합니다.
Problem📄

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

 

프로그래머스

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

programmers.co.kr


Think🤔
class Solution {
    public int solution(String[] babbling) {
        int answer = 0;
        
        for(int i=0; i<babbling.length; i++){
            if(wordVerify(babbling[i])){
                answer++;
            }
        }
        
        return answer;
    }
    
    public boolean wordVerify(String word){
        boolean flag = true;
        
        word = word.replaceFirst("aya","").replaceFirst("ye","").replaceFirst("woo","").replaceFirst("ma","");
        
        String word2 = word;
        if(word.length() > 0){
            flag = false;
            word2 = word.replace("aya","").replace("ye","").replace("woo","").replace("ma","");
            if(!word.equals(word2) && word2.length() > 0){
                flag = false;
            }
        }
        
        
        return flag;
    }
}

Solution✍
class Solution {
    public int solution(String[] babbling) {
        int answer = 0;
        
        String word = babbling[0];
        for(int i=0; i<babbling.length; i++){
            word = babbling[i];
            if(word.contains("ayaaya") || word.contains("yeye") || word.contains("woowoo") || word.contains("mama")){
                continue;
            }
            word = word.replace("aya"," ").replace("ye"," ").replace("woo"," ").replace("ma"," ");
            word = word.replace(" ",""); // " "이거로 안하고 바로 replace ""를 할 경우 단어가 붙어버려서 aayaya일 경우의 값과 동일하지 못함
            if(word.length() == 0){
                answer++;
            }
        }
        
        return answer;
    }
}

Review🤩

contain는 붙여서 쓸 수 없다.

 

문제에서 아기는 연속해서 발음하기 어렵다고 한다.

고로 "ayayemaaya" 가 나와서 "ayaaya"케이스와 다르게 발음을 할 수 있다.(replaceFirst를 못쓰는 이유)


 

알고리즘 풀이 방법입니다.
문제(Problem) -> 생각(Think) -> 해결책(Solution) -> 리뷰(Review) 를 통해서 정리해서 작성합니다.
Problem📄

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

 

프로그래머스

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

programmers.co.kr


Think🤔
import java.util.ArrayList;

class Solution {
    public int solution(int n, int m, int[] section) { // 8 4 236
        int answer = 0;
        int start = section[0]; // 2
        int end = section[section.length-1]; // 6
        
        for(int i=0; i<end; i++){
            if(section[i] >= start && section[i] <= end){
                start = section[i];
                end = end - m + 1;
                answer++;
            }
        }
        
        
        return answer;
    }
}

첫번째 작성코드 62점

마지막 값에서 타일 바른갯수를 삭제하고 카운트를 해줬다.

 

이 코드가 안되는 이유는 end는 자릿수를 검사해야 되는데 반복문을 깎아버려서 애초에 맞지 않는 코드


Solution✍
import java.util.ArrayList;

class Solution {
    public int solution(int n, int m, int[] section) {
        int answer = 0;
        int start = section[0];
        answer++; // section의 길이 최소 1 한번은 무조건 칠함
        
        for(int i=0; i<section.length; i++){
            if(start + m > section[i]){ // 칠해져있으면 section의 값은 패쓰
                continue;
            }
            answer++;
            start = section[i];
        }
        
        
        return answer;
    }
}

Review🤩

 

알고리즘 풀이 방법입니다.
문제(Problem) -> 생각(Think) -> 해결책(Solution) -> 리뷰(Review) 를 통해서 정리해서 작성합니다.
Problem📄

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

 

프로그래머스

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

programmers.co.kr


Think🤔

약수를 구하는 방법이 이 문제의 핵심포인트

약수를 효율적으로 구해야지 100,000까지 반복문을 돌면서 시간이 많이 안걸리게 할 수 있다.


Solution✍
class Solution {
    public int solution(int number, int limit, int power) {
        int answer = 0;
        int tmp = 1;
        
        for(int i=1; i<=number; i++){
            tmp = measure(i);
            if(tmp > limit){
                answer += power;
            }else{
                answer += tmp;
            }
        }
        
        return answer;
    }
    
    public  int measure(int x){
        int count = 0;
        int sqrtX = (int) Math.sqrt(x); // x의 제곱근 계산
        for (int i = 1; i <= sqrtX; i++) {
            if (x % i == 0) {
                count += 2; // i와 x/i 두 개의 약수를 찾음
            }
        }
        // 완전제곱수의 경우 중복으로 센 약수 하나를 뺌
        if (sqrtX * sqrtX == x) {
            count--;
        }
        
        return count;
    }
}
// number의 약수를 구하는 부분이 핵심
// Math.sqrt(number);를 이용한다. 100,000까지의 약수를 구하면 시간이 너무 오래걸려서 돌지 않을것..

Review🤩

100 1 2 5 10 20 50 100 -> 7개
10   1 2 5 10 -> 4개

25 -> 3개
5 -> 2개

400 -> 1 2 4 5 8 10 20 40 50 80 100 200 400 -> 13
20 -> 1 2 4 5 10 20 -> 6개 

 

처음에 이런식으로 규칙을 찾았는데 해당 방법이 맞지 않음

 

25 같은 경우 완전수

 

sqrt는 제곱근으로 두 개의 약수를 찾은 후 완전수 인 경우 1 , 5 , 5 , 25 으로 5가 두번 들어가기 때문에 1개를 빼줘야 한다.


 

알고리즘 풀이 방법입니다.
문제(Problem) -> 생각(Think) -> 해결책(Solution) -> 리뷰(Review) 를 통해서 정리해서 작성합니다.
Problem📄

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

 

프로그래머스

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

programmers.co.kr


Think🤔
class Solution {
    public String solution(String[] cards1, String[] cards2, String[] goal) {
        String answer = "No";
        
        if(cards1[1].equals(goal[1+cards2.length])){
            answer = "Yes";
        }
        return answer;
    }
}

단순하게 cards1 하나 나오고 cards2가 무조건 3번째로 들어오는 줄 알았음.

 

class Solution {
    public String solution(String[] cards1, String[] cards2, String[] goal) {
        // cards1 - 0
        // cards2 - 0
        // goal에 cards1 이나오면 1 추가 되고 맞는지 확인
        // 순서가 바뀌면 안됨
        String answer = "Yes";
        
        int one = cards1.length-1;
        int two = cards2.length-1;
        
        for(int i=goal.length-1; i>0; i--){
            if(goal[i].equals(cards1[one])){
                one--;
            }else if(goal[i].equals(cards2[two])){
                two--;
            }else{
                answer = "No";
                break;
            }
        }
        
        
        return answer;
    }
}

0부터 시작해보고 , 마지막부터 줄이면서 해봤는데 런타임 에러 나면서 72점 몇개의 테스트 케이스에서 통과하지 못함


Solution✍
class Solution {
    public String solution(String[] cards1, String[] cards2, String[] goal) {
        // cards1 - 0
        // cards2 - 0
        // goal에 cards1 이나오면 1 추가 되고 맞는지 확인
        // 순서가 바뀌면 안됨
        // 반례 : cards1 과 cards2의 값을 띈 다음 값 부터 확인할 수 있음
        // idx가 넘어가면 안되므로 max값 비교까지
        // 뒤에부터 비교하면 cards1,cards2의 마지막 인덱스 값이 없을경우 No를 출력하기 때문에 앞에서 부터 출력해야함
        String answer = "Yes";
        
        int one = cards1.length;
        int oneidx = 0;
        int two = cards2.length;
        int twoidx = 0;
        
        for(int i=0; i<goal.length; i++){
            if(oneidx < one && goal[i].equals(cards1[oneidx])){
                oneidx++;
            }else if(twoidx < two && goal[i].equals(cards2[twoidx])){
                twoidx++;
            }else{
                answer = "No";
                break;
            }
        }
        
        return answer;
    }
}

Review🤩

다양한 경우의 수를 생각하고 반례를 이용해서 풀 수 있도록하자


 

+ Recent posts