Leetcode中回文题

这篇文章专门看Leetcode中回文的题目,根据题目要求不一样,所用的方法也是差别本大。基本也是递归和DP吧。

题目一:Palindrome Partitioning

Given a string s, partition s such that every substring of the partition is a palindrome. Returnall possible parlindrome of s

思路:因为要枚举所有可能的解,我觉得还是递归比较合适,但是会有大量的substr 和 isParlindrome判断,一定程度上会影响速度。这里可以从isPalindrome的判断和备忘录两个点进行优化。

class Solution {
public:
bool isPalindrome(string s){
        int i,j;
        for(i=0, j=s.length()-1; i<j; i++, j--)
            if(s[i]!=s[j]) break;
        if(i>=j) return true;
        return false;
    }
    
    bool partition(vector<vector<string> >& res, vector<string>& palin, string s, int start){
        if(s.length()==start){
            res.push_back(palin);
            //palin.clear();
            return true;
        }
        int flag=false;
        for(int j=1;j+start<=s.length();j++){
            string tmp=s.substr(start, j);
            if(isPalindrome(tmp)){
                palin.push_back(tmp);
                if(partition(res, palin, s, start+j))
                    flag=true;
                
                palin.pop_back();
                
            }
        }
        return flag;
    }
    
    vector<vector<string> > partition(string s) {
        vector<vector<string> > res;
        vector<string> palin;
        partition(res, palin, s, 0);
        return res;
    }
    
};
这道题固然什么优化都没有,就过了~~,不过可能是这种递归形式我见多了,递归有 bool返回值!利用这里的bool返回值也是关键点之一。


题目二:Palindrome Partitioning II

Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partition of s.

思路:这样要求最小cuts数,如果按照之前的思路,枚举出所有的情况,选出cuts最小的,能求得解,但肯定超时,因为没有必要求那么多。不能用递归了,只能从DP着手了。若干用DP的方法求解,总得找到递推关系式吧。

class Solution {
public:
    bool isPalindrome(string s, vector<vector<int> >& table){
    	int n = s.size();
        table.resize(n);
        for(int i=0; i<n; i++) { 
            table[i].resize(n);
            for (int j=0; j<n; j++) table[i][j] = false;
        }

    	for(int len=1; len<=n; len++){
    		for(int i=0; i+len<=n; i++){
    			int j=i+len-1;
    			if(i==j) table[i][j]=true;   //一个元素的情况 
    			else if(j==i+1 && s[i]==s[j]) table[i][j]=true;  //两个元素 
    			else if(table[i+1][j-1] && s[i]==s[j]) table[i][j]=true; 
    		}	
    	}
    } 
    
    int minCut(string s){
    	int n=s.length();
    	vector<vector<int> > table;
    	vector<int> mincut(n+1,n);//最小割初始化为最大值
    	isPalindrome(s, table);
    	
    	mincut[0]=0;
    
    	for(int i=1; i<=n; i++){  //end
    		for(int j=0; j<i; j++){  //start
    			if(table[j][i-1]){
    				if(j==0){    
    					mincut[i]=0;
    					break;
    				}
    				else
    					mincut[i]=min(mincut[i], mincut[j]+1);	
    			}	
    		}	
    	}
    	return mincut[n];
    }  
};
说明:该解法有两个特点,其一是生成palindrome判定矩阵table。该矩阵的生成同样利用的DP的思想,利用 len 和 i 控制矩阵的遍历。而不是直接控制 i,j,好处是后者没有的。其二是求最小割,用mincut[i]表示0-i的字串需要的最小割。


题目三:Valid Palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

思路:这道题利用简单的两个指针往中间遍历,就轻轻松松的搞定。总而言之,是一种遍历就可以解决的问题。

class Solution {
public:
    bool isPalindrome(string s) {
        if(s.length()==0 || s.length()==1) return true;
      
        int i,j;
        for(i=0,j=s.length()-1; i<j;){
            if(s[i]>='a'&&s[i]<='z' || s[i]>='A'&&s[i]<='Z' || s[i]>='0'&&s[i]<='9'){
                if(s[i]>='A'&&s[i]<='Z') s[i]=tolower(s[i]);
                if(s[j]>='a'&&s[j]<='z' || s[j]>='A'&&s[j]<='Z' ||  s[j]>='0'&&s[j]<='9'){
                    if(s[j]>='A'&&s[j]<='Z') s[j]=tolower(s[j]);
                    if(s[i]!=s[j]) break;
                    else{
                        i++;
                        j--;
                    }
                }
                else j--;
            }
            else i++;
        }
        if(i>=j) return true;
        return false;
    }
};


题目四: Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.

思路:这道题重点在如何分解数字吧。一个难点是求数x的阶乘,处理不当会导致溢出。。。(这貌似是所有数字处理题都应该注意的问题)。

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0) return false;
        
        int y=x;
        int order=1;
        while(y/10>0){  //乘法容易溢出,而除法则可以避免
            order*=10;
            y/=10;
        }
            
        while(x>0){
            int a=x%10;
            int b=x/order;
            if(a!=b) return false;
            x=(x%order)/10;
            order/=100;
        }
        return true;
    }
};


题目五:Longest Palindromic Substring

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

思路:之前说过求palindrome 矩阵是用的DP方法,用table[i][j]表示从i到j是否为一合法的回文,在此基础上,稍加改造就可以得到子回文序列的长度。

class Solution {
public:
  
    string longestPalindrome(string s) {
        int n=s.length();
        if(n==0 || n==1) return s;
        
        bool table[1001][1001];
        memset(table, 0, sizeof(table));
        //vector<vector<bool> > table(n, vector<bool>(n, false)); 超时!
        
        //don't use substr
        //don't use vector of vector
        int maxlen=1, start=0;
    	for(int len=1; len<=n; len++){
    		for(int i=0; i+len<=n; i++){
    			int j=i+len-1;
    			if(i==j) table[i][j]=true;   //一个元素的情况 
    			else if(j==i+1 && s[i]==s[j]) table[i][j]=true;  //两个元素 
    			else if(table[i+1][j-1] && s[i]==s[j]) table[i][j]=true; 
    			
    			if(table[i][j] && j-i+1 > maxlen){
    			    maxlen=j-i+1;
    			    start=i;
    			}
    		}	
    	}
        
        return s.substr(start,maxlen);
    }
};

到此,回文题全部处理完了,总体来说用DP求回文,还有用DP求最小割和最长字串都挺有意思的。


补充一套题:回文构词法


题目六:Anagrams

Given an array of strings, return all groups of strings that are anagrams. Note: all inputs will be in lower-case. For example: input: ["tea", "and", "ate", "eat", "den"], output: ["tea", "ate", "eat"].  回文构词法(anagrams)是指颠倒字母顺序组成的单词。

思路:将原单词排序,并建立排序后的词和排序前的词的关联,利用map<string, int>即可。

class Solution {
public:
    vector<string> anagrams(vector<string> &strs) {
        vector<string> res;
        int n=strs.size();
        if(n==0) return res;
        
        map<string, int> anagram;
        for(int i=0; i<n; i++){
            string tmp=strs[i];
            sort(tmp.begin(), tmp.end());
            if(anagram.count(tmp)==0){  //该词第一次出现,什么都不做
                anagram[tmp]=i;
            }
            else{ 
                if(anagram[tmp]>=0){ //相似的词第二次出现
                    res.push_back(strs[anagram[tmp]]); 
                    anagram[tmp]=-1; //将第一个出现的词放入res,并做好标记
                }
                res.push_back(strs[i]);
            }
        }
        return res;
    }
};

说明:这里的map为啥不建成map<string, string>,一来省地方,二来好识别访问过(将index设为-1)。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据提供的引用内容,有三种方法可以解决LeetCode上的最长回文子串问。 方法一是使用扩展心法优化,即从左向右遍历字符串,找到连续相同字符组成的子串作为扩展心,然后从该心向左右扩展,找到最长的回文子串。这个方法的时间复杂度为O(n²)。\[1\] 方法二是直接循环字符串,判断子串是否是回文子串,然后得到最长回文子串。这个方法的时间复杂度为O(n³),效率较低。\[2\] 方法三是双层for循环遍历所有子串可能,然后再对比是否反向和正向是一样的。这个方法的时间复杂度也为O(n³),效率较低。\[3\] 综上所述,方法一是解决LeetCode最长回文子串问的最优解法。 #### 引用[.reference_title] - *1* [LeetCode_5_最长回文子串](https://blog.csdn.net/qq_38975553/article/details/109222153)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Leetcode-最长回文子串](https://blog.csdn.net/duffon_ze/article/details/86691293)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [LeetCode 第5:最长回文子串(Python3解法)](https://blog.csdn.net/weixin_43490422/article/details/126479629)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值