Example
Input : 3 , [Good, Time, Study]
Output : [dooG, emiT, ydutS]
My answer:
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.lang.StringBuilder;
class StringReversalProcessor {
public static void main(String[] args) {
StringReversalProcessor t = new StringReversalProcessor();
Scanner kb = new Scanner(System.in);
int cnt = kb.nextInt();
String[] s = new String[cnt];
for(int i = 0; i < cnt; i++) {
s[i] = kb.next();
}
for(String x : t.solution2(s)) {
System.out.println(x);
}
}
List<String> solution(String[] s) {
List<String> list = new ArrayList<>();
for(String x : s) {
String tmp = x;
char[] c = tmp.toCharArray();
int rt = tmp.length() - 1;
for(int lt = 0; lt < tmp.length()/2; lt++) {
char t = c[lt];
c[lt] = c[rt];
c[rt] = t;
rt--;
}
list.add(String.valueOf(c));
}
return list;
}
List<String> solution2(String[] s) {
List<String> list = new ArrayList<>();
for(String x : s) {
String tmp = x;
StringBuilder sb = new StringBuilder(tmp);
list.add(sb.reverse().toString());
}
return list;
}
}
The 'solution' method:
1. This method takes an array of strings as input and returns a list of reversed strings.
2. It initializes an empty 'ArrayList' named 'list' to store the reversed strings.
3. It iterates over each string 'x' in the input array 's'.
4. Inside the loop, it converts the string 'x' to a character array 'c' and performs an in-place reversal of the characters using a two-pointer approach.
5. The loop swaps characters from both ends of the string towards the center until it reaches the middle of the string.
6. The reversed character array is then converted back to a string and added to the 'list'.
7. After processing all strings, the method returns the 'list' containing reversed strings.
The 'solution2' method:
1. This method is similar to the 'solution' method but uses a different approach to reverse the strings.
2. It also takes an array of strings as input and returns a list of reversed strings.
3. Inside the loop, it creates a 'StringBuilder' named 'sb' from the string 'x'.
4. It then calls the 'reverse' method on the 'StringBuilder' to reverse its content.
5. The reversed content is converted back to a string and added to the 'list'.
6. Like the previous method, after processing all strings, the method returns the 'list' containing reversed strings.
'Language > Algorithm' 카테고리의 다른 글
Palindrome Checker - 2 (0) | 2023.08.30 |
---|---|
Palindrome Checker (0) | 2023.08.28 |
Remove duplicate characters (0) | 2023.08.26 |
Reverse Alphabetic Characters (0) | 2023.08.25 |
Find the longest word (0) | 2023.08.23 |