baru003のブログ

baruの雑記兼備忘録

AOJ 0063

・問題リンクPalindrome

・コメント
ポイントは文字列の先頭と末尾から中心に向かって見ていき、文字列の中心に到達する前に
str[i]!=str[length-i]
となってしまった時点でその文字列は非対称であることがわかります。
また、length-1のところまで見ていくことが出来ればその文字列は対称であるといえるのでカウント++します。

・ソース

import java.util.*;

public class P0063 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int cnt = 0;
		while (sc.hasNext()) {
			String str = sc.next();
			char[] a = str.toCharArray();
			int len = str.length();
			int temp = len;
			if(len==1){
				cnt++;
				continue;
			}
			for (int i = 0; i < len - 1; i++) {
				if (a[i] != a[temp - 1]) {
					break;
				} else if (a[i] == a[temp - 1]) {
					temp--;
				}
				if (i == (len - 1) / 2) {
					cnt++;
					break;
				}
			}
		}
		System.out.println(cnt);
	}
}