When I run my code I get runtime error .I am trying to run this on geeksforgeeks, if it has something to do with the error. It gives segmentation fault as an error.
Segmentation Fault (SIGSEGV)
Here is my code
#include<bits/stdc .h>
using namespace std;
class Solution{
public:
bool isPalindrome(string str,int start,int end){
while(start<end){
if(str[start]!=str[end]) return false;
start ;
end--;
}
return true;
}
void solve(vector<string>& v,int &ans,string &str, int i){
if(i==str.length()){
if(v.size()<ans) ans=v.size();
return;
}
for(int j=i;j<str.length();j ){
if(isPalindrome(str,i,j)) {
v.push_back(str.substr(i,j-i 1));
solve(v,ans,str,i);
v.pop_back();
}
}
}
int palindromicPartition(string str)
{
vector<string> v;
int ans = INT_MAX;
solve(v,ans,str,0);
return ans-1;
}
};
int main(){
int t;
cin>>t;
while(t--){
string str;
cin>>str;
solution ob;
cout<<ob.palindromicPartition(str)<<"\n";
}
return 0;
}
CodePudding user response:
You are trying to push_back()
a string
into a vector<int>
. You have to cast the string to an int
- this can be achieved with std::stoi
.
v.push_back(std::stoi(str.substr(i, j - i 1)));
vector<string> v;
int ans = INT_MAX;
solve(v, ans, str, 0);
You are passing a vector<string>
to a function that accepts a vector<int>
. Declare v
to be a vector<int>
.
CodePudding user response:
void solve(vector<string>& v,int &ans,string &str, int i){
if(i==str.length()){
if(v.size()<ans) ans=v.size();
return;
}
for(int j=i;j<str.length();j ){
if(isPalindrome(str,i,j)) {
v.push_back(str.substr(i,j-i 1));
solve(v,ans,str,i);
v.pop_back();
}
}
}
Bro i have corrected your code issue was this you were making vector of
string data type but in solve function you change the type to int of vector
, since the vector passed to function was of string type so your vector
argument of function should be of string type ,Thankyou