[編程題] 迴文串 java 蘑菇街2016研發工程師在線編程題


給定一個字符串,問是否能通過添加一個字母將其變爲迴文串。

輸入描述:
一行一個由小寫字母構成的字符串,字符串長度小於等於10。


輸出描述:
輸出答案(YES\NO).
示例1

輸入

coco

輸出

YES

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			String str = sc.next();
			char[] chs = str.toCharArray();
			System.out.println(sovle(chs));
		}
		sc.close();
	}

	/**
	 * 使用雙指針實現
	 * 
	 * @param chs
	 * @return
	 */
	private static String sovle(char[] chs) {
		int start = 0;
		int end = chs.length - 1;
		String res = "YES";
		while (start <= end) {
			if (chs[start] == chs[end]) {
				++start;
				--end;
				// 相當於刪除後面的元素(在前面插入一個元素)
			} else if (chs[start] == chs[end - 1]) {
				--end;
			} else if (chs[start + 1] == chs[end]) {
				++start;
			} else {
				res = "NO";
				// 注意
				break;
			}
		}
		return res;
	}
}


在其它地方看到一種思路:既然能通過增加一個字符變成迴文串,那一定也可以通過刪除一個字符變成迴文串。用一個循環,每次循環依次刪掉一個字符,然後檢查新串是否是迴文串,看起來簡單方便許多。

for (int i = 0; i < strlen(s); i++) {
    strcpy(tmp, s);
    for (int j = i; j < strlen(s); j++)
         tmp[j] = tmp[j+1]; // 刪掉tmp[j],把後面的向前移動
    if (tmp is 迴文串)
         return true;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章