코딩테스트/Programmers

[Programmers] 이상한 문자 만들기

주니어주니 2023. 8. 26. 18:14

 

 

 

문자 사이의 공백을 어떻게 처리해야 하나... 

 

* 내 풀이 -> 틀림

import java.util.*;

class Solution {
    public String solution(String s) {          
        StringBuilder sb = new StringBuilder();
        
        String[] arr = s.trim().split(" ");      
        
        for(String str : arr) {     
            for(int i=0; i<str.length(); i++) {
                if (i == 0 || i%2 == 0) {
                    sb.append(Character.toUpperCase(str.charAt(i))); 
                } else if (i%2 != 0) {
                    sb.append(Character.toLowerCase(str.charAt(i)));
                } 
            }
            sb.append(" "); 
        }
        
        return sb.toString().trim();
    }
}

 

 

 

String.split(String regex, int limit) -> 공백 유지

String str = "수박:사과:배:메론:::";

// limit = 0
String[] arr = str.split(":");		// {"수박", "사과", "배", "메론"}

// limit > 0
String[] arr = str.split(":", 3);	// {"수박", "사과", "배:메론"}

// limit < 0
String[] arr = str.split(":", -1);	// {"수박", "사과", "배", "메론", "", "", ""}

 

 

 

* 다른 사람 풀이

 

import java.util.*;

class Solution {
    public String solution(String s) {          
        StringBuilder sb = new StringBuilder();
        
        String[] arr = s.split("");     // [t,r,y, , ,h,e,l,l,o]
        
        int index = 0;
        
        for(int i=0; i<arr.length; i++) {     
            if (arr[i].equals(" ")) {
                index = 0;
            } else if (index % 2 == 0) {
                arr[i] = arr[i].toUpperCase();
                index++;
            } else {
                arr[i] = arr[i].toLowerCase();
                index++;
            }
            sb.append(arr[i]);
        }
        
        return sb.toString();
    }
}