728x90
- 앞에서 읽을 때, 뒤에서 읽을 때나 같은 문자열 => 회문 문자열
(입력)
Moon
gooG
(출력)
# subString, equalsIgnoreCase 사용
public class Main {
private String solution(String s) {
String answer = "YES";
for (int i=0; i<s.length()/2; i++) {
if (!s.substring(i, i+1).equalsIgnoreCase(s.substring(s.length()-i-1, s.length()-i))) {
return "NO";
}
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
System.out.println(T.solution("Moon"));
System.out.println(T.solution("gooG"));
}
}
# toUpperCase, charAt 사용
public class Main {
private String solution(String s) {
String answer = "YES";
s = s.toUpperCase();
for (int i=0; i<s.length()/2; i++) {
if (s.charAt(i) != s.charAt(s.length()-i-1)) {
return "NO";
}
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
System.out.println(T.solution("Moon"));
System.out.println(T.solution("gooG"));
}
}
# StringBuffer, reverse, equalsIgnoreCase 사용
public class Main {
private String solution(String s) {
String answer = "NO";
String reversedS = new StringBuffer(s).reverse().toString();
if (s.equalsIgnoreCase(reversedS)) answer = "YES";
return answer;
}
public static void main(String[] args) {
Main T = new Main();
System.out.println(T.solution("Moon"));
System.out.println(T.solution("gooG"));
}
}
# StringBuilder, reverse, equalsIgnoreCase 사용
public class Main {
private String solution(String s) {
String answer = "NO";
String reversedS = new StringBuilder(s).reverse().toString();
if (s.equalsIgnoreCase(reversedS)) answer = "YES";
return answer;
}
public static void main(String[] args) {
Main T = new Main();
System.out.println(T.solution("Moon"));
System.out.println(T.solution("gooG"));
}
}
# String -> char[] -> List 로 변환 후 Collections.reverse, Collectors.joining() 사용
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
private String solution(String s) {
String answer = "NO";
char[] arr = s.toCharArray(); // String -> char[]
List<Character> list = new ArrayList<>();
for (char c: arr) { // char[] -> List
list.add(c);
}
Collections.reverse(list);
if (list.stream() // Stream<Character>
.map(String::valueOf) // Stream<String>
.collect(Collectors.joining())
.equalsIgnoreCase(s))
answer = "YES";
return answer;
}
public static void main(String[] args) {
Main T = new Main();
System.out.println(T.solution("Moon"));
System.out.println(T.solution("gooG"));
}
}
반응형
'전.java' 카테고리의 다른 글
[Java] 특정 문자 뒤집기 (0) | 2023.01.27 |
---|---|
[Java] 회문 문자열 2 (0) | 2023.01.27 |
[Java] 문자열 압축 (1) | 2023.01.26 |
[Java] 백준 10807 개수 세기 (1) | 2023.01.16 |
[Java] 백준 14681 사분면 고르기 (0) | 2023.01.16 |