Palindrome Index
傳送門:?Palindrome Index
Problem Statement
You are given a string of lower case letters. Your task is to figure out the index of the character on whose removal it will make the string a palindrome. There will always be a valid solution.?
In case the string is already a palindrome, then?-1?is also a valid answer along with possible indices.
Input Format
The first line contains?T, i.e. the number of test cases.
T?lines follow, each containing a string.
Output Format
Print the position (0 index) of the letter by removing which the string turns into a palindrome. For a string, such as
bcbcwe can remove?b?at index 0 or?c?at index 3. Both answers are accepted.
Constraints?
1≤T≤20?
1≤?length of string?≤100005?
All characters are Latin lower case indexed.
Sample Input
3 aaab baa aaaSample Output
3 0 -1Explanation
In the given input,?T?= 3,
- For input?aaab, we can see that removing?b?from the string makes the string a palindrome, hence the position 3.
- For input?baa, removing?b?from the string makes the string palindrome, hence the position 0.
- As the string?aaa?is already a palindrome, you can output 0, 1 or 2 as removal of any of the characters still maintains the palindrome property. Or you can print -1 as this is already a palindrome.
讀題時需注意:
題目中先說 “There will always be a valid solution. ”,然后才說“In case the string is already a palindrome, then?-1?is also a valid answer along with possible indices.”。注意體會這句話,我們首先應注意到,即使輸入的字符串S是個回文串,也可以刪除某個字母使其仍為回文串。如果|S|為奇數,則刪除中間那個字母,結果串仍為回文串。如果|S|為偶數則刪除中間兩個相等字符中的任一個,結果串也回文。
完全暴力的解法:
枚舉要刪除的字母,檢查結果串是否回文。復雜度O(N^2)。
只是這解法過于暴力,TLE。
下面就要引入這道題給我的最大啟示了:
尋找有助于簡化問題的必要條件
考慮一下上面的單純暴力算法有那些冗余計算。
首先必須指出一個問題:優(yōu)化算法的途徑是充分考慮問題的特殊性。
其次要注意到:題目要求的是存在性判別,上面的算法枚舉被刪除字符的位置是無可厚非的。
接著考慮一下使上面的算法達到最壞情況的數據:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab
在這種情況下,上述算法必須枚舉到最后一個字符才能確定答案。
我們不難發(fā)現(xiàn)一個問題
?
?
?
轉載于:https://www.cnblogs.com/Patt/p/4467609.html
新人創(chuàng)作打卡挑戰(zhàn)賽發(fā)博客就能抽獎!定制產品紅包拿不停!總結
以上是生活随笔為你收集整理的Palindrome Index的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php内核探索 [转]
- 下一篇: 3.4 黑盒测试用例的设计方法 之 等价