`

k-palindrome

 
阅读更多

Question:

A k-palindrome is a string which transforms into a palindrome on removing at most k characters.

Given a string S, and an interger K, print “YES” if S is a k-palindrome; otherwise print “NO”.
Constraints:
S has at most 20,000 characters.
0<=k<=30

Sample Test Case#1:
Input – abxa 1
Output – YES
Sample Test Case#2:
Input – abdxa 1
Output – No

one solution:
Let's say p[n] is a palindrom with lenght n. Let l will be begining, end e the end of a palindrom. Then we can see that:
1) p[l] == p[h], then we need to check p[l+1] == p[h – 1], i.e abcba, where p[l] == a == p[h]
2a) p[l] != p[h], then we need to check p[l+1],p[h] (we removed p[l])
2b) p[l] != p[h], then we need to check p[l], p[h-1], (we removed p[h])

bool isKPalindrom(string input, int k)
{
        int answers[input.size() + 1][input.size() + 1];
        int N = input.size();
        for(int i = 0; i <= N; i++)
                for(int j = 0; j <= N; j++)
                        answers[i][j] = 0;


        for(int gap = 1; gap <= N; gap++)
        {
                int l = 1;
                int h = l + gap;
                for(; h <= N; l++, h++)
                {
                        if(input[l-1] == input[h - 1])
                                answers[l][h] = answers[l+1][h-1];
                        else
                                answers[l][h] = 1 + min(answers[l+1][h], answers[l][h-1]);
                }
        }

        return answers[1][N] <= k;
}

 

The complexity is O(n^2).

Another solution:

The question asks if we can transform the given string S into its reverse deleting at most K letters.
We could modify the traditional Edit-Distance algorithm, considering only deletions, and check if this edit distance is <= K. There is a problem though. S can have length = 20,000 and the Edit-Distance algorithm takes O(N^2). Which is too slow.

(From here on, I'll assume you're familiar with the Edit-Distance algorithm and its DP matrix)

However, we can take advantage of K. We are only interested *if* manage to delete K letters. This means that any position more than K positions away from the main diagonal is useless because its edit distance must exceed those K deletions.

Since we are comparing the string with its reverse, we will do at most K deletions and K insertions (to make them equal). Thus, we need to check if the ModifiedEditDistance is <= 2*K
Here's the code:

int kpalindrome(string &a, int k){
    int asize = a.size();
    string b = a;
    reverse(b.begin(), b.end());
    int bsize = asize;
    vector<vector<int> > dp(asize+1, vector<int>(bsize+1, 1000));
    for(int i = 0; i <= asize; i++){
        dp[i][0] = i;
		dp[0][i] = i;
    }
        
    for(int i = 1; i <= asize; i++){
        for(int j = max(1, i-k); j <= min(bsize, i+k); j++){
            if(a[i-1] == b[j-1]){
                dp[i][j] = dp[i-1][j-1];
            }
            dp[i][j] = min(dp[i][j], dp[i-1][j]+1);
            dp[i][j] = min(dp[i][j], dp[i][j-1]+1);
        }
    }
    if(dp[asize][bsize]<= 2*k)    return dp[asize][bsize];
    else return -1;
}

int _tmain(int argc, _TCHAR* argv[])
{
	string a = "abxa";
	int ret = kpalindrome(a, 1);
	cout<<ret<<endl;
	return 0;
}

 

We only process 2*K+1 columns per row. So this algorithm works in O(N*K) which is fast enough.

 

From:

https://linzhongzl.wordpress.com/2013/11/25/k-palindrome/

分享到:
评论

相关推荐

    LeetCode最全代码

    ...The number of questions is increasing recently. Here is the classification of all `468` questions. ...I'll keep updating for full summary and better solutions....|-----|---------------- | --------------- |...

    程序员面试宝典LeetCode刷题手册

    9. Palindrome Number 11. Container With Most Water 13. Roman to Integer 15. 3Sum 16. 3Sum Closest 17. Letter Combinations of a Phone Number 18. 4Sum 19. Remove Nth Node From End of List 20. Valid ...

    Company-Wise-Coding-Questions

    5. Closest Palindrome 6. Check Array Contains Contigous Integer 7. Pairs with Positive and Negative Values 8. Maximum Tip Calculator 9. Prime Number of Set Bits 10. Reverse Each Word in String 11. ...

    lrucacheleetcode-leetcode:leetcode

    Palindrome Number 11. Container With Most Water 12. Integer to Roman 13. Roman to Integer 14. Longest Common Prefix 15. 3Sum 20. Valid Parentheses 21. Merge Two Sorted Lists 22. Generate Parentheses ...

    leetcode中325题python-leetcode:leetcode

    leetcode中325题python leetcode 以 参考 和 Hash相关 1_两数之和 387_字符串中的第一个唯一字符 链表操作 2 ...删除链表的倒数第N个节点 ...k个一组翻转链表 ...palindrome-linked-list 双指针遍历/滑动

    cpp-算法精粹

    Reverse Nodes in k-Group Copy List with Random Pointer Linked List Cycle Linked List Cycle II Reorder List LRU Cache Palindrome Linked List 字符串 Valid Palindrome Implement strStr() String to Integer...

    javalruleetcode-leetcode:力码解决方案

    [回文链表](md/Palindrome Linked List.md) - 2015-10-06 [数字一](md/数字一.md) - 2015-10-06 [使用栈实现队列](md/使用栈实现队列.md) - 2015-10-06 [BST 中的第 K 个最小元素](md/BST.md 中的第 K 个最小元素) -...

    判断链表是否为回文链表leetcode-Leetcode-solutions:Leetcode问题的思考和解决方案

    判断链表是否为回文链表 ...)=k,其中k=1到numOfRows当k&gt;=numOfRows时,对应中间的元素,存储位置应该是(numOfRows-1)-(i-(numOfRows-1)) #longest common prefix 最长的公共前缀长度不会超过列表中最短的字符

    回文数(Python操作字符串实现)

    这也算是一道经典的题目了,判断一个数是否是一个回文数,何为回文数,即从左往右读和从右往左读都一样。这里我的思路是把这个数从两端遍历,判断其是否相等,若有... print('{} is not a palindrome'.format(num)) k

    编写Python代码,实现寻找反素数的功能

    代码使用一个函数is_palindrome,判断一个数是否是回文数,使用字符串反转的方法 代码使用一个函数is_reversible_prime,判断一个数是否是反素数,使用上述两个函数和字符串反转的方法 代码使用input函数,从控制台...

    lrucacheleetcode-leetcode-1:leetcode-1

    求两有序数列的中位数,可泛化为求两有序数列的第k位数,二分法 5. Longest Palindromic Substring 最长回文子串,补符号,记忆 6. ZigZag Conversion 观察规律 7. Reverse Integer 翻转整数 8. String to Integer ...

    代码 动态规划 特殊数据结构搜索、枚举

    1043 Cheapest Palindrome 1045 Cake Cutting 1049 Brackets 特殊数据结构 1004 Prince Ray’s Puzzle 树状数组 1010 选队长 二叉树 1022 Longest Common Sequence 也可用二叉搜索树(nlog时间)解决,见llj的书 ...

    leetcode跳跃-subond::squid:LeetCodeGo题解,每周日更新

    Palindrome Number 11 盛最多水的容器 中等 数组 14 最长公共前缀 15 三数之和 19 Remove Nth Node From End of List 中等 链表 20 有效的字符串/有效的括号 21 合并两个有序链表 23 合并K个排序链表 24 两两交换...

    算法:python和C中的算法

    3级 :对随机数数组实施快速排序(python)| O(nlogn)| 3级:实施计数排序| O(n + k)| 2级 :在python中实现计数排序| O(n + k)| 2级:实现基数排序| O(数字*(n +基数))| 4级特里:实现特里并执行插入,...

    leetcode338-Leetcode:一些过滤leetcode问题的解决方案

    234.Palindrome 链表: | 725. 分部分拆分链表: | 328.奇偶链表:| 哈希表: 问题及解决方法: 1.二和:| 594.最长和谐子序列:| 128.最长连续序列:| 数组和矩阵 问题及解决方法: 283.移零:| 566.重塑矩阵: | ...

Global site tag (gtag.js) - Google Analytics