I don't know where is the error in my code ? can someone help me to fix it .
My code :
#include<bits/stdc .h>
using namespace std;
#define ll long long
void solution() {
string s;
ll k;
cin >> s >> k;
for(int i=0; i<=s.length()-k; i ) {
for(int r=k-1; r<s.length(); r ){
cout << s.substr(i,r) << endl;
}
}
}
int main() {
ll t;
cin >> t;
while(t--){
solution();
}
return 0;
}
input :
1
ABCD 3
Expected output:
ABC
BCD
Actual output:
AB
ABC
BC
BCD
CodePudding user response:
I have no idea why you need a nested for loop. Why isn't this just simply:
void solution() {
string s;
ll k;
cin >> s >> k;
for(int i = 0; i <= s.length() - k; i ) {
cout << s.substr(i, k) << endl;
}
}
CodePudding user response:
Here's a way to get all substring with the length given:
#include<string>
#include<iostream>
int main() {
int input = 0;
std::string str = "";
std::cin >> input >> str; //This is the length of substring you wanna get
for (int i = str.size() - input; i >= 0; i--){
std::cout << str.substr(i, input) << " "; //output the result from end to begin
}
}
You will get a decreasing-order answer.