最长回文字符串出错,求解

shiter
人工智能领域优质创作者
博客专家认证
2016-08-18 12:14:11
"esbtzjaaijqkgmtaajpsdfiqtvxsgfvijpxrvxgfumsuprzlyvhclgkhccmcnquukivlpnjlfteljvykbddtrpmxzcrdqinsnlsteonhcegtkoszzonkwjevlasgjlcquzuhdmmkhfniozhuphcfkeobturbuoefhmtgcvhlsezvkpgfebbdbhiuwdcftenihseorykdguoqotqyscwymtjejpdzqepjkadtftzwebxwyuqwyeegwxhroaaymusddwnjkvsvrwwsmolmidoybsotaqufhepinkkxicvzrgbgsarmizugbvtzfxghkhthzpuetufqvigmyhmlsgfaaqmmlblxbqxpluhaawqkdluwfirfngbhdkjjyfsxglsnakskcbsyafqpwmwmoxjwlhjduayqyzmpkmrjhbqyhongfdxmuwaqgjkcpatgbrqdllbzodnrifvhcfvgbixbwywanivsdjnbrgskyifgvksadvgzzzuogzcukskjxbohofdimkmyqypyuexypwnjlrfpbtkqyngvxjcwvngmilgwbpcsseoywetatfjijsbcekaixvqreelnlmdonknmxerjjhvmqiztsgjkijjtcyetuygqgsikxctvpxrqtuhxreidhwcklkkjayvqdzqqapgdqaapefzjfngdvjsiiivnkfimqkkucltgavwlakcfyhnpgmqxgfyjziliyqhugphhjtlllgtlcsibfdktzhcfuallqlonbsgyyvvyarvaxmchtyrtkgekkmhejwvsuumhcfcyncgeqtltfmhtlsfswaqpmwpjwgvksvazhwyrzwhyjjdbphhjcmurdcgtbvpkhbkpirhysrpcrntetacyfvgjivhaxgpqhbjahruuejdmaghoaquhiafjqaionbrjbjksxaezosxqmncejjptcksnoq"


思路是翻转过来,求解最长公共子串
Output:
"cltg"
Expected:
"yvvy"

哪里出bug了,求解

// leetcode5.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<string>
#include<vector>
using namespace std;

string longestCommonSubstring(string s1, string s2)
{
int N = s1.size(), M = s2.size(), len = 0, r = -1;
vector<vector<int>> mem(N, vector<int>(M, 0));
for (int i = 0; i<N; ++i) {
for (int j = 0; j<M; ++j) {
if (s1[i] == s2[j]) {
mem[i][j] = (i == 0 || j == 0) ? 1 : mem[i - 1][j - 1] + 1;
if (mem[i][j] > len) len = mem[i][j], r = i;
}
else {
mem[i][j] = 0;
}
}
}
return s1.substr(r - len + 1, len);
}

string longestPalindrome(string s)
{
if (s.empty())return NULL;

string s1(s.rbegin(), s.rend());

return longestCommonSubstring(s, s1);

}


int main()
{
string s = longestPalindrome("a");
return 0;
}




...全文
701 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
shiter 2017-04-16
  • 打赏
  • 举报
回复

string longestPalindrome(string s) {
    if (s.empty()) return "";
    if (s.size() == 1) return s;
    int min_start = 0, max_len = 1;
    for (int i = 0; i < s.size();) {
      if (s.size() - i <= max_len / 2) break;
      int j = i, k = i;
      while (k < s.size()-1 && s[k+1] == s[k]) ++k; // Skip duplicate characters.
      i = k+1;
      while (k < s.size()-1 && j > 0 && s[k + 1] == s[j - 1]) { ++k; --j; } // Expand.
      int new_len = k - j + 1;
      if (new_len > max_len) { min_start = j; max_len = new_len; }
    }
    return s.substr(min_start, max_len);
}

shiter 2017-04-16
  • 打赏
  • 举报
回复


string longestPalindrome(string s) {
    if (s.empty()) return "";
    if (s.size() == 1) return s;
    int min_start = 0, max_len = 1;
    for (int i = 0; i < s.size();) {
      if (s.size() - i <= max_len / 2) break;
      int j = i, k = i;
      while (k < s.size()-1 && s[k+1] == s[k]) ++k; // Skip duplicate characters.
      i = k+1;
      while (k < s.size()-1 && j > 0 && s[k + 1] == s[j - 1]) { ++k; --j; } // Expand.
      int new_len = k - j + 1;
      if (new_len > max_len) { min_start = j; max_len = new_len; }
    }
    return s.substr(min_start, max_len);
}string longestPalindrome(string s) {
    if (s.empty()) return "";
    if (s.size() == 1) return s;
    int min_start = 0, max_len = 1;
    for (int i = 0; i < s.size();) {
      if (s.size() - i <= max_len / 2) break;
      int j = i, k = i;
      while (k < s.size()-1 && s[k+1] == s[k]) ++k; // Skip duplicate characters.
      i = k+1;
      while (k < s.size()-1 && j > 0 && s[k + 1] == s[j - 1]) { ++k; --j; } // Expand.
      int new_len = k - j + 1;
      if (new_len > max_len) { min_start = j; max_len = new_len; }
    }
    return s.substr(min_start, max_len);
}
shiter 2016-08-23
  • 打赏
  • 举报
回复

// leetcode5.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<string>
#include<vector>
using namespace std;

bool fun(int low, int high, const char *str, int length)
{
	if (length == 0 || length == 1)
		return    true;
	if (str[low] != str[high])
		return    false;
	return fun(low + 1, high - 1, str, length - 2);
}



string longestCommonSubstring(string s1, string s2)
{
	int N = s1.size(), M = s2.size(), len = 0, r = -1;
	vector<vector<int>> mem(N, vector<int>(M, 0));
	for (int i = 0; i<N; ++i) {
		for (int j = 0; j<M; ++j) {
			if (s1[i] == s2[j]) {
				mem[i][j] = (i == 0 || j == 0) ? 1 : mem[i - 1][j - 1] + 1;
				if (mem[i][j] > len) len = mem[i][j], r = i;
			}
			else {
				mem[i][j] = 0;
			}
		}
	}
	string s_result = s1.substr(r - len + 1, len);
	int s_length = s_result.length();
	if (fun(0, s_length-1, s_result.c_str(), s_length))
	{
		return s_result;
	}
	else
	{
		string tmp1 = s1.substr(r + 1 , s1.length() - r +1);
		string tmp2(tmp1.rbegin(), tmp1.rend());
		return longestCommonSubstring(tmp1,tmp2);
	}
}

string longestPalindrome(string s)
{
	if (s.empty())return NULL;

	string s1(s.rbegin(), s.rend());

	return longestCommonSubstring(s, s1);

}


int main()
{
	string s = longestPalindrome("cltgmkogtlc");
    return 0;
}

//class Solution {
//public:
//	std::string longestPalindrome(std::string s) {
//		if (s.size() < 2)
//			return s;//特殊情况特殊处理
//		int len = s.size(), max_left = 0, max_len = 1, left, right;
//		for (int start = 0; start < len && len - start > max_len / 2;)
//		{
//			left = right = start;
//			while (right < len - 1 && s[right + 1] == s[right])
//				++right;//当中间有重复时跳过
//
//			start = right + 1;
//
//			while (right < len - 1 && left > 0 && s[right + 1] == s[left - 1])
//			{
//				++right;
//				--left;
//			}
//
//			if (max_len < right - left + 1) {
//				max_left = left;
//				max_len = right - left + 1;
//			}
//		}
//		return s.substr(max_left, max_len);
//	}
//};

//bool isHuiwen(int begin, int end, const char* s)
//{
//	if (end == begin || end<begin)
//	{
//		return true;
//	}
//	if (s[begin] != s[end])
//	{
//		return false;
//	}
//	return isHuiwen(begin + 1, end - 1, s);
//}


难道非得这么搞?
shiter 2016-08-23
  • 打赏
  • 举报
回复
引用 2 楼 lm_whales 的回复:
举例

“cltgmkogtlc”
这个字符串中
cltg 是它和 逆串 的最长公共子串,但并不是回文串


引用 6 楼 zhao4zhong1 的回复:
代码功能归根结底不是别人帮自己看或讲解或注释出来的;而是被自己静下心来花足够长的时间和精力亲自动手单步或设断点或对执行到某步获得的中间结果显示或写到日志文件中一步一步分析出来的。
提醒:再牛×的老师也无法代替学生自己领悟和上厕所!
单步调试和设断点调试(VS IDE中编译连接通过以后,按F10或F11键单步执行,按Shift+F11退出当前函数;在某行按F9设断点后按F5执行停在该断点处。)是程序员必须掌握的技能之一。




问下大牛,怎么看里面形参的值呢?
赵4老师 2016-08-23
  • 打赏
  • 举报
回复
不要依赖调试器输出复杂数据结构!而要将复杂数据结构的整个内容在处理它的每一步使用一小段代码按自己很容易理解的格式输出,非常有助于调试!或者可以说是“基础设施”
shiter 2016-08-19
  • 打赏
  • 举报
回复

// leetcode5.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<string>
#include<vector>
using namespace std;

int fun(int low, int high, const char *str, int length)
{
	if (length == 0 || length == 1)
		return    1;
	if (str[low] != str[high])
		return    0;
	return fun(low + 1, high - 1, str, length - 2);
}



string longestCommonSubstring(string s1, string s2)
{
	int N = s1.size(), M = s2.size(), len = 0, r = -1;
	vector<vector<int>> mem(N, vector<int>(M, 0));
	for (int i = 0; i<N; ++i) {
		for (int j = 0; j<M; ++j) {
			if (s1[i] == s2[j]) {
				mem[i][j] = (i == 0 || j == 0) ? 1 : mem[i - 1][j - 1] + 1;
				if (mem[i][j] > len) len = mem[i][j], r = i;
			}
			else {
				mem[i][j] = 0;
			}
		}
	}
	string s_result = s1.substr(r - len + 1, len);
	int s_length = s_result.length();
	if (fun(0, s_length, s_result.c_str(), s_length))
	{
		return s_result;
	}
	else
	{
		return longestCommonSubstring(s1.substr(s_length,r + 1- s_length),s2);
	}
}

string longestPalindrome(string s)
{
	if (s.empty())return NULL;

	string s1(s.rbegin(), s.rend());

	return longestCommonSubstring(s, s1);

}


int main()
{
	string s = longestPalindrome("aaa");
    return 0;
}
求高手,这个判断还有点小问题
赵4老师 2016-08-19
  • 打赏
  • 举报
回复
代码功能归根结底不是别人帮自己看或讲解或注释出来的;而是被自己静下心来花足够长的时间和精力亲自动手单步或设断点或对执行到某步获得的中间结果显示或写到日志文件中一步一步分析出来的。 提醒:再牛×的老师也无法代替学生自己领悟和上厕所! 单步调试和设断点调试(VS IDE中编译连接通过以后,按F10或F11键单步执行,按Shift+F11退出当前函数;在某行按F9设断点后按F5执行停在该断点处。)是程序员必须掌握的技能之一。
flying_music 2016-08-18
  • 打赏
  • 举报
回复
楼主思路有点儿问题,反过来的最长公共子串不一定是原串的回文子串,就拿你给的例子来说,原串中有“cltg”也有“gtlc”,它们两个翻转以后就成了公共子串了,但它本身并不是回文串,所以才会出现这样的错误,这是我以前刷题时写的一篇博客,有需要可以参考一下 http://blog.csdn.net/cyfcsd/article/details/48102139
lm_whales 2016-08-18
  • 打赏
  • 举报
回复
举例 “cltgmkogtlc” 这个字符串中 cltg 是它和 逆串 的最长公共子串,但并不是回文串
lm_whales 2016-08-18
  • 打赏
  • 举报
回复
最长公共字串未必是回文串 所以,应该判断最公共长回文子串 所以求出子串前要先判断是否回文,不是回文不参与计算
shiter 2016-08-18
  • 打赏
  • 举报
回复
引用 1 楼 lm_whales 的回复:
最长公共字串未必是回文串 所以,应该判断最公共长回文子串 所以求出子串前要先判断是否回文,不是回文不参与计算
引用 3 楼 cyfcsd 的回复:
楼主思路有点儿问题,反过来的最长公共子串不一定是原串的回文子串,就拿你给的例子来说,原串中有“cltg”也有“gtlc”,它们两个翻转以后就成了公共子串了,但它本身并不是回文串,所以才会出现这样的错误,这是我以前刷题时写的一篇博客,有需要可以参考一下 http://blog.csdn.net/cyfcsd/article/details/48102139
Solution Approach #1 (Longest Common Substring) [Accepted] Common mistake Some people will be tempted to come up with a quick solution, which is unfortunately flawed (however can be corrected easily): Reverse SS and become S'S ​′ ​​ . Find the longest common substring between SS and S'S ​′ ​​ , which must also be the longest palindromic substring. This seemed to work, let’s see some examples below. For example, S = ''caba" S=''caba", S ′ = ''abac'' S′=''abac''. The longest common substring between SS and S'S ​′ ​​ is ''aba'' ''aba'', which is the answer. Let’s try another example: S = ''abacdfgdcaba'' S=''abacdfgdcaba'', S ′ = ''abacdgfdcaba'' S′=''abacdgfdcaba''. The longest common substring between SS and S'S ​′ ​​ is ''abacd'' ''abacd''. Clearly, this is not a valid palindrome. Algorithm We could see that the longest common substring method fails when there exists a reversed copy of a non-palindromic substring in some other part of SS. To rectify this, each time we find a longest common substring candidate, we check if the substring’s indices are the same as the reversed substring’s original indices. If it is, then we attempt to update the longest palindrome found so far; if not, we skip this and find the next candidate. This gives us an O(n^2)O(n ​2 ​​ ) Dynamic Programming solution which uses O(n^2)O(n ​2 ​​ ) space (could be improved to use O(n)O(n) space). Please read more about Longest Common Substring here. 奥,看来是要先判断一下是不是回文

65,176

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧