'palindrome'에 해당하는 글 1건

회문(Palindrome)이란?

단어나 구 또는 문장 등에서 앞으로 읽으나 뒤로 읽으나 같은 것을 말한다.

예를 들어서 "구로구"와 같은 단어나 "다들잠들다"와 같은 문장이 있다.

 

회문(Palindrome) 판별 소스 (Java)

public class Solution {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int num = 0;
		String[] strArry;
		num = sc.nextInt();
		
		strArry = new String[num];
		
		for(int i = 0; i < num; i++) {
			strArry[i] = sc.next();
		}
		
		for(int s = 0; s < num; s++) {
			int count = 0;
			
			System.out.print("#" + (s+1) + " ");
			
			for(int i = 0; i < strArry[s].length() - 2; i++) {
				for(int j = i + 2; j < strArry[s].length(); j++) {
					Palindrome p = new Palindrome(strArry[s].substring(i, j + 1));
					if(p.isPalindrome()) {
						count++;
						System.out.print(strArry[s].substring(i, j + 1) + " ");
					}
				}
			}
			
			if(count != 0) {
				System.out.println(","+ count);
			} else {
				System.out.println(count);
			}
		}
		
		sc.close();
	}
}

class Palindrome {
	String str;
	
	public Palindrome(String str) {
		this.str = str;
	}
	
	public boolean isPalindrome() {
		boolean isTrue = true;
		
		for(int i = 0; i < str.length(); i++) {
			if(str.charAt(i) != str.charAt(str.length() - 1 - i)) {
				isTrue = false;
			}
		}
		
		return isTrue;
	}
}

원하는 개수만큼 문장을 입력한 후, 그 문장에서 회문이 몇 개 있는지 출력해주는 소스이다.

3글자 이상으로 이루어진 경우에만 회문으로 인정했다.

 

 

'프로그래밍 > 알고리즘' 카테고리의 다른 글

순차 탐색(Sequential Search)이란?  (0) 2017.10.18
탐색(Search)이란?  (0) 2017.10.18
선택 정렬(Selection Sort)  (0) 2017.10.08
삽입 정렬(Insert Sort)  (0) 2017.10.04
정렬(Sort)이란?  (0) 2017.10.04

WRITTEN BY
김치치즈스마일
세계정복!

,