【LeetCode】 Longest Palindrome Substring

题目链接:http://oj.leetcode.com/problems/longest-palindromic-substring/

题目描述:

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.


题目意思:找出给定字符串中最常的回文字串,输入保证有且仅有一个正确结果。


解法一:

暴力求解,时间复杂度O(n^2).提交会超时。

代码如下:

string longestPalindrome(string s) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int result = 0;
    	int start = -1;
    	int len = s.length();
    	if(len <= 0) return NULL;
    	if(len == 1) return s;
    	for(int i=0;i < len; ++i){
    		int j = i+1;
    		while(j < len){
    			if( isPalindrome(s, i, j)){
    				int temp = j - i + 1;
    				if(temp > result){
    					result = temp;
    					start = i;
    				}
    			}
    			j++;
    		}
    	}
	    return s.substr(start, result);
    }
    
    bool isPalindrome(string s, int start, int end){
        while(start < end){
            if(s[start++] != s[end--])
                return false;
        }
        return true;
    }

解法二:

暴力求解,时间复杂度O(n^2)。能通过,rp好吗!

思路:分别以每个位置为中心向两边扩展。

代码如下:

string longestPalindrome(string s) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
    	int result = 0;
    	int start = 0;
    	int len = s.length();
    	if(len <= 0) return NULL;
    	if(len == 1) return s;
    	for(int i=0;i < len; ++i){
    		int f = i+1,b = i;
    		int temp;
    		while(b >=0 && f < len && s[b] == s[f]) 
    			b--, f++;
    		temp = f - b - 1;
    		if(temp > result){
    			result = temp;
    			start =  b + 1;
    		}
    
    		f = i+1, b = i-1;
    		while(b >=0 && f < len && s[b] == s[f]) 
    			b--, f++;
    		temp = f - b - 1 ;
    		if(temp > result){
    			result = temp;
    			start =  b + 1;
    		}
    	}
    	return s.substr(start, result);
    }

未完待续…………DP和O(n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值