ALGORITHM

[JAVA] 알고리즘 : 문자열 - 단어 뒤집기

연듀 2022. 6. 20. 15:39

 

StringBuilder 사용

import java.io.*;
import java.util.*;

public class Main {
    public ArrayList<String> solution(int n, String[] str){
        ArrayList<String> answer = new ArrayList<>();

        for(String x:str){
            String tmp = new StringBuilder(x).reverse().toString(); // StringBuilder: 새로운 객체를 생성하지 않는다.
            answer.add(tmp);
        }
        return answer;
    }
    public static void main(String[] args) throws IOException {
        Main T = new Main();
        Scanner kb = new Scanner(System.in);
        int n = kb.nextInt();
        String[] str = new String[n];

        for(int i=0; i<n; i++){
            str[i] = kb.next();
        }
        for(String x : T.solution(n, str)){ // ArrayList를 받음
            System.out.println(x);
        }
    }

}

 

직접 뒤집기

import java.io.*;
import java.util.*;

public class Main {
    public ArrayList<String> solution(int n, String[] str){
        ArrayList<String> answer = new ArrayList<>();
        for(String x : str){
            char[] s = x.toCharArray(); // 문자를 문자 배열로 만듬
            int lt = 0, rt=x.length()-1;
            while(lt<rt){
                char tmp = s[lt];
                s[lt] = s[rt];
                s[rt] = tmp;
                lt++;
                rt--;
            }
            String tmp = String.valueOf(s); // 문자 배열 s를 string으로
            answer.add(tmp);
        }

        return answer;
    }
    public static void main(String[] args) throws IOException {
        Main T = new Main();
        Scanner kb = new Scanner(System.in);
        int n = kb.nextInt();
        String[] str = new String[n];

        for(int i=0; i<n; i++){
            str[i] = kb.next();
        }
        for(String x : T.solution(n, str)){ // ArrayList를 받음
            System.out.println(x);
        }
    }

}