๊ด€๋ฆฌ ๋ฉ”๋‰ด

Coding Planet

8. ์œ ํšจํ•œ ํŒฐ๋ฆฐ๋“œ๋กฌ (Palindrome) - replaceAll ๋ณธ๋ฌธ

๐ŸŽ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ/์•Œ๊ณ ๋ฆฌ์ฆ˜

8. ์œ ํšจํ•œ ํŒฐ๋ฆฐ๋“œ๋กฌ (Palindrome) - replaceAll

jhj.sharon 2023. 5. 8. 14:11
๋ฐ˜์‘ํ˜•

1. ๋ฌธ์ œ ์š”๊ตฌ์‚ฌํ•ญ

  • ๋ฌธ์ž์—ด์ด ์ž…๋ ฅ๋˜๋ฉด ํ•ด๋‹น ๋ฌธ์ž์—ด์ด ํŒฐ๋ฆฐ๋“œ๋กฌ์ด๋ฉด "YES", ์•„๋‹ˆ๋ฉด “NO"๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”.
  • ๋‹จ ํšŒ๋ฌธ์„ ๊ฒ€์‚ฌํ•  ๋•Œ ์•ŒํŒŒ๋ฒณ๋งŒ ๊ฐ€์ง€๊ณ  ํšŒ๋ฌธ์„ ๊ฒ€์‚ฌํ•˜๋ฉฐ, ๋Œ€์†Œ๋ฌธ์ž๋ฅผ ๊ตฌ๋ถ„ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

 

 

2. ๋‚ด ํ’€์ด - replaceAll(), reverse()

  • ์ˆซ์ž, ํŠน์ˆ˜๋ฌธ์ž ๋“ฑ์ด ์„ž์ธ ๋ฌธ์ž์—ด์—์„œ ์•ŒํŒŒ๋ฒณ๋งŒ ์ถ”์ถœํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” replaceAll()์„ ์‚ฌ์šฉํ•œ๋‹ค. ์ด๋•Œ ์•ŒํŒŒ๋ฒณ ์ด์™ธ์˜ ๊ฒƒ๋“ค์„ " " (๊ณต๋ฐฑ๋ฌธ์ž)๋กœ ๋ฐ”๊ฟ”์ค€๋‹ค.
  • ํšŒ๋ฌธ ๋น„๊ต๋Š” ์ด์ „ ํฌ์ŠคํŠธ์˜ reverse()๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค.

 

import java.util.Scanner;

public class PalindromeChecker  {
	public String solution(String str) {
		//1. ์ •๊ทœ์‹์„ ์ด์šฉํ•˜์—ฌ ์•ŒํŒŒ๋ฒณ์„ ์ถ”์ถœํ•˜๊ณ  ๋Œ€๋ฌธ์ž๋กœ ์ „ํ™˜ํ•œ๋‹ค.
		String s = str.replaceAll("[^A-Za-z]", "").toUpperCase();
		
		//2. reverse()๋กœ ๋น„๊ตํ•˜๊ธฐ
		String tmp = new StringBuilder(s).reverse().toString();
		if(s.equals(tmp)) return "YES";
		else return "NO";
		
	
	}

	public static void main(String[] args) {

		PalindromeChecker  T = new PalindromeChecker();
		
		Scanner kb = new Scanner(System.in);
		String str = kb.nextLine();
		
			System.out.println(T.solution(str));
		
	}

}

 

๋ฐ˜์‘ํ˜•
Comments