I am getting this above error and I am unable to debug the cause for it. Can anyone help me with this (what's causing this error)?
Problem Statement: Finding Longest Common Prefix
Source: https://leetcode.com/problems/longest-common-prefix/
Code(Using Divide and Conquer):
#include <iostream>
#include <unordered_map>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string common_prefix(string left, string right){
int minim = min(left.length(), right.length());
for (int i=0; i<minim; i++){
if (left[i]!=right[i]){
return left.substr(0, i);
}
}
return "" ;
}
string dap(vector<string>& a, int l, int r){
if (l==r) return a[l];
int mid = (l+r)/2;
string left = dap(a, l, mid);
string right = dap(a, mid+1, r);
return common_prefix(left, right);
}
string longestCommonPrefix(vector<string>& strs) {
return dap(strs, 0, strs.size());
}
};
int main()
{
Solution s;
vector<string> st{"flower","flow","flight"};
string ans = s.longestCommonPrefix(st);
cout << ans;
}
Traceback:
Runtime Error
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_M_create
Input:
["flower","flow","flight"]
Expected Output:
"fl"