https://leetcode.com/problems/reverse-words-in-a-string/

코드설명

문자열(String) + 구현(Implementation)  를 활용합니다.

 

제가 접근한 방법은, 직접 빈칸일경우와 Word 인 경우에 대해 로직을 다르게 하여 처리합니다.

물론, Split 함수를 활용할 경우 더 간편해집니다.

 

혹은, two pointer 방식으로 split 한뒤 양쪽의 단어들을 서로 바꾸어나가는 방식도 존재합니다.

코드

정답코드1입니다.

String의 idx를 조절하여 처리합니다.

class Solution {
    Stack<String> st = new Stack<>();
    StringBuilder answer = new StringBuilder();
    public String reverseWords(String s) {
        int idx = 0;
        boolean isBeforeEmptySpace = true;
        StringBuilder sb = new StringBuilder();
        Stack<String> st = new Stack<>();
        while(idx < s.length()){
            if(s.charAt(idx) == ' '){
                if(isBeforeEmptySpace == false){
                    st.push(sb.toString());
                    sb = new StringBuilder();
                    isBeforeEmptySpace = true;
                }
                idx += 1;
            }
            else if(s.charAt(idx) !=' '){
                // System.out.println(s.charAt(idx));
                sb.append(s.charAt(idx));
                isBeforeEmptySpace = false;
                idx++;
            }
        }

        //sb.length() > 0 인 경우를 처리하는 이유는
        //아래에서 answer.append(' '); 로 
        //st에 sb.length()가 0 이더라도 ' '가 추가되기 때문입니다.
        if (sb.length() > 0) {
            st.push(sb.toString());
        }

        while (!st.isEmpty()) {
            answer.append(st.pop());
            if (!st.isEmpty()) { // 마지막 단어 뒤에는 공백을 추가하지 않음
                answer.append(' ');
            }
        }
        return answer.toString();    
    }
}

 

처음에 틀린 오답코드입니다.

class Solution {
    Stack<String> st = new Stack<>();
    StringBuilder answer = new StringBuilder();
    public String reverseWords(String s) {
        int idx = 0;
        boolean isBeforeEmptySpace = true;
        StringBuilder sb = new StringBuilder();
        Stack<String> st = new Stack<>();
        while(idx < s.length()){
            if(s.charAt(idx) == ' ' ){
                if(isBeforeEmptySpace == false){
                    st.push(sb.toString());
                    sb = new StringBuilder();
                }
                idx += 1;
            }
            else if( s.charAt(idx) !=' '){
                System.out.println(s.charAt(idx));
                sb.append(s.charAt(idx));
                isBeforeEmptySpace = false;
                idx++;
            }
        }
        st.push(sb.toString());
        sb = new StringBuilder();
        
        while(!st.isEmpty()){
            answer.append(st.pop()).append(' ');
        }

        answer.deleteCharAt(answer.length() - 1);
        return answer.toString();
    }
}

+ Recent posts