您的位置:首页 > 其它

leetcode No5. Longest Palindromic Substring

2016-06-15 11:41 246 查看

Question:

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.

题目大意是找出字符串中最长的回文字符串

Algorithm:(最笨的方法)

遍历字符串,从当前字符往两边走,如果一样就继续,不一样停止并返回这个字符串的起始下标、终止下标,长度


Submitted Code:

class Solution {
public:
    string longestPalindrome(string s) {
            int N = s.size();
            if(N<2)return s;
<span style="white-space:pre">	</span>        string t;
<span style="white-space:pre">	</span>        string res;
<span style="white-space:pre">	</span>        int max = 0;      //max length of palindromic substring 
<span style="white-space:pre">		</span>int begin = 0;     //begin position of max palindromic substring length 
<span style="white-space:pre">	</span>      int end = 0;       //end  position of max palindromic substring length 
<span style="white-space:pre">		</span>for (int i = 0; i<(N-1); i++)
<span style="white-space:pre">		</span>{
<span style="white-space:pre">			</span>t.push_back(s[i]);
<span style="white-space:pre">			</span>t.push_back('#');  //插入'#'的目的是为了区分奇偶
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>t.push_back(s[N - 1]);
<span style="white-space:pre">		</span>for (int j = 0; j<(2 * N - 1); j++)
<span style="white-space:pre">		</span>{
<span style="white-space:pre">			</span>int m = j;
<span style="white-space:pre">			</span>int n = 0;       //j往两边走的步数
<span style="white-space:pre">			</span>int count = 0;
<span style="white-space:pre">			</span>while ((m - n) >= 0 && (m + n)<(2 * N - 1))    
<span style="white-space:pre">			</span>{
<span style="white-space:pre">				</span>if (t[m - n] == t[m + n])
<span style="white-space:pre">					</span>count++;
<span style="white-space:pre">				</span>else
<span style="white-space:pre">				</span>    break;
<span style="white-space:pre">				</span>n++;
<span style="white-space:pre">			</span>}
<span style="white-space:pre">			</span>if (t[m-n+1] == '#')count--;    //例如"#b#"多算了一次
<span style="white-space:pre">			</span>if (count>max)
<span style="white-space:pre">			</span>{
<span style="white-space:pre">				</span>begin = m - n + 1;
<span style="white-space:pre">				</span>end = m + n - 1;
<span style="white-space:pre">				</span>max = count;
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>for (int i = begin, j = 0; i <= end; i++)
<span style="white-space:pre">		</span>{
<span style="white-space:pre">			</span>if (t[i] != '#')
<span style="white-space:pre">			</span>{
<span style="white-space:pre">				</span>res.push_back(t[i]);
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>}
        return res;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: