ALGORITHM

[JAVA] 알고리즘 : 단어 뒤집기

연듀 2022. 12. 19. 10:51

 

StringBuilder reverse() 사용

public static ArrayList<String> solution(String[] str){
    ArrayList<String> answer = new ArrayList<>();
    for(String x : str){
        String tmp = new StringBuilder(x).reverse().toString();
        answer.add(tmp);
    }
    return answer;
}

 

 

 

toCharArray로 배열로 바꿔 풀이 

public static ArrayList<String> solution2(String[] str){
    ArrayList<String> answer = new ArrayList<>();
    for(String x :str){
        char[] s = x.toCharArray();
        int left = 0, right = x.length()-1;
        while(left<right){
            char tmp = s[left];
            s[left] = s[right];
            s[right] = tmp;
            left++;
            right--;
        }
        String result = String.valueOf(s);
        answer.add(result);
    }
    return answer;
}