今天刷leetcode时刷到了求最长回文字符串的问题,一开始就是暴力解,101个用例过了46个,不行
#include <stdio.h>
#include <sstream>
#include <iostream>
#include <stdio.h>
#include <sstream>
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
#include <algorithm>
#include<cstring>
using namespace std;
class Solution {
bool judge(int i,int j,string s) {
while (i < j) {
if (s[i] != s[j])
{
return false;
}
else
{
i++; j--;
}
}
return true;
}
public:
string longestPalindrome(string &s) {
if (s == "")
return "";
int begin = 0;
int L = 1;
for (int length = s.length(); length >=2; length--) {
for (int i = 0; i + length <= s.length(); i++) {
if (judge(i, i + length - 1,s) && length>L) {
L = length;
begin = i;
return s.substr(begin, L);
}
}
}
return s.substr(begin,L);
}
};
后来又大佬说传参中s变成&s,内存的节约和效率都提高很多,试了一下,暴力直接过了?!!!
写个博客,以此记录