자료구조와 알고리듬 With Java/[zerobase] Algorithm

Part.01연습문제 풀이 [zerobase]

계란💕 2022. 5. 11. 12:05

1. 숫자를 거꾸로 출력하기

<hide/>
package src;
public class Practice1 {
    public static void solution(int num) {

        int answer = 0;
        if(0 == num) {
            System.out.println(answer);
            return;
        }
        String str = "";
        if(num < 0) {
            num *= -1;
            while (0 != num) {
                str += num % 10;
                num /= 10;
            }
            answer = Integer.parseInt(str);
            System.out.println(-1 * answer);
            return;
        }
            while(0 != num){
                str += num % 10;
                num /= 10;
            }
        answer = Integer.parseInt(str);
        System.out.println(answer);
    }

    public static void main(String[] args) {
        // Test code
        solution(12345);
        solution(-12345);
        solution(100);
        solution(0);
    }
}

  Note) 실행 결과

 

 

2. ASCII Code (대소문자 변환하여 출력하기)

  - (int)'a' - (int)'A'를 통해 step을 구한다. 

  - 입력받은 값이 대문자일 경우, step을 더하고 소문자인 경우에는 step을 빼준다.

<hide/>
import java.util.Scanner;

public class Practice2 {
    public static void solution() {
        Scanner scan = new Scanner(System.in);
        System.out.print("알파벳 입력: ");
        char input = scan.nextLine().charAt(0);
        int output = 0;
        int step = (int)'a' - (int)'A';
        
        if('a' <= input && input <= 'z'){
            output = (int)input - step;
            System.out.println("대문자 변환: "+ (char)output);
        }else if('A' <= input && input <= 'Z'){
            output = (int)input + step;
            System.out.println("소문자 변환: "+ (char)output);
        }else{
            System.out.println("입력하신 값이 알파벳이 아닙니다.");
        }
    }

    public static void reference() {
        int a = (int)'a';
        System.out.println("a = " + a);
        int z = (int)'z';
        System.out.println("z = " + z);
        int A = (int)'A';
        System.out.println("A = " + A);
        int Z = (int)'Z';
        System.out.println("Z = " + Z);
        int etc = (int)'%';
        System.out.println("etc = " + etc);
    }

    public static void main(String[] args) {
        reference();    // 아스키 코드 참고
        solution();
    }
}

  Note) 실행 결과

 

 

 

3. replace를 사용하지 않고 String의 replace 기능 구현하기

<hide/>

public class Practice3 {
    public static String solution(char[] str, char[] find, char[] to){
       int idx = 0;
       String replaceStr = "";
       char[] replaceBucket = str.clone();

       do{
            idx  = findIndex(replaceBucket, find);
            if(idx != -1){
                for(int i = 0; i < idx; ++i){
                    replaceStr += replaceBucket[i];
                }
                for(int i = 0; i < to.length; ++i){
                    replaceStr += to[i];
                }
                for(int i = idx + find.length; i < replaceBucket.length; ++i){
                    replaceStr += replaceBucket[i];
                }
                replaceBucket = replaceStr.toCharArray();
                replaceStr = "";
            }

       }while(idx != -1);
            replaceStr = new String(replaceBucket);
            return replaceStr;
    }
    public static int findIndex(char[] str, char[] find){
        int idx = -1;
        boolean isMatch = false;

        for(int i = 0; i < str.length; ++i){
            if(str[i] == find[0]    &&      str.length - i >= find.length){// 찾으려는 데이터보다 문자열의 길이가  길어야 가능
                isMatch = true;
                for(int j = 1; j < find.length; ++j){
                    if(str[i + j] != find[j]){  // 한 글자씩 비교
                        isMatch = false;
                        break;
                    }
                }
            }
            if(isMatch == true){
                idx = i;    // 찾은 위치를 넣어준다.
                break;
            }
        }
        return idx;
    }

    public static void main(String[] args) {
        // Test code
        String str = "Hello Java, Nice to meet you! Java is fun!";
        String find = "Java";
        String to = "자바";

        // 기존 String replace
        System.out.println(str.replace(find, to));

        // 자체 구현 replace
        char[] strExArr = str.toCharArray();
        char[] findArr = find.toCharArray();
        char[] toArr = to.toCharArray();
        System.out.println(solution(strExArr, findArr, toArr));

        strExArr = "POP".toCharArray();
        findArr = "P".toCharArray();
        toArr = "W".toCharArray();
        System.out.println(solution(strExArr, findArr, toArr));
    }
}

  

 

4. 삼각형 출력하기

  - type5는 상단부(index: 0 ~ n/2 + 1)와 하단부를 나누어 출력한다.

  - 공백을 먼저 출력하고 그 다음에 별은 각 줄마다 2i - 1개씩 출력한다.

  - 하단부의 row 인덱스는 3, 2, 1이 들어가도록 한다.

    -> for(i = n / 2; i > 0 ; --i)

<hide/>

public class Practice4 {
    public static void solution(int n, int type) {

        if(1 == type) type1(n);
        if(2 == type) type2(n);
        if(3 == type) type3(n);
        if(4 == type) type4(n);
        if(5 == type) type5(n);
    }

    public static void type1(int n) {
        System.out.println("== Type1 ==");
        for(int i = 0;i < n; ++i){
            for(int j = 0;j < n; ++j){
                System.out.print("*");
            }
            System.out.println();
        }
        System.out.println();
    }

    public static void type2(int n) {
        System.out.println("== Type2 ==");
        for(int i = 1;i <= n; ++i){
            for(int j = 1;j <= i; ++j){
                System.out.print("*");
            }
            System.out.println();
        }
        System.out.println();
    }

    public static void type3(int n) {
        System.out.println("== Type3 ==");

        for(int i = 1;i <= n; ++i){
            for(int j = 1;j <= n; ++j){
                if( j <= n - i) {
                    System.out.print(" ");
                    continue;
                }
                System.out.print("*");
            }
            System.out.println();
        }
        System.out.println();
    }

    public static void type4(int n) {
        System.out.println("== Type4 ==");

        for(int i = 1; i <= n; ++i){
            for(int j = 1; j <= 2 * n - 1; ++j){
                if( j <= n - i || n + i <= j ) {
                    System.out.print(" ");
                    continue;
                }
                System.out.print("*");
            }
            System.out.println();
        }
        System.out.println();
    }

    public static void type5(int n) {
        System.out.println("== Type5 ==");
        // 상단부
        for(int  i = 0; i <= n/2; ++i) {
            for(int j = 0; j < n / 2 - i; ++j){
                System.out.print(" ");
            }
            for(int j = 0; j < 2 * i + 1 ; ++j){
                System.out.print("*");
            }
            System.out.println();
        }
        // 하단부
        for(int i = n / 2; i > 0 ; --i){
            for(int j = 0; j < n /2 + 1 - i; ++j ){
                System.out.print(" ");
            }
            for(int j = 0; j < i * 2 - 1; ++j){
                System.out.print("*");
            }
            System.out.println();
        }
        System.out.println();
    }

    public static void main(String[] args) {
        // Test code
        solution(5, 1);
        solution(5, 2);
        solution(5, 3);
        solution(5, 4);
        solution(5, 5);
    }
}

 

  Note) 실행 결과

 

 

5. 어떤 두 벽을 고르면 가장 많은 물을 담을 수 있는가

<hide/>
public class Practice5 {
    public static int solution(int[] height) {
        int left = 0;
        int right = height.length - 1;
        int maxArea = 0;

        while(left < right){
            int x = right - left;
            int y = height[left] < height[right] ?  height[left] : height[right];   // 물이 넘치지 않도록 작은 쪽을 기준으로 계산한다.
            int currArea = x * y;
            maxArea = currArea > maxArea ? currArea : maxArea;

            if(height[left] < height[right]){
                ++left;
                continue;
            }
            --right;
        }
        return maxArea;
    }

    public static void main(String[] args) {
        // Test code
        int[] height = {1, 8, 6, 2, 5, 4, 8, 3, 7};
        System.out.println(solution(height));
        height = new int[]{5, 3, 9, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2};
        System.out.println(solution(height));
    }
}