E. *_*urg 2 c++ string char backtracking c++11
我正在练习我的编码技能,我正在解决以下回溯问题(原始指南的解决方案也在那里)。
问题总结:
给定一个字符串,您需要打印所有可能的字符串,这些字符串可以通过在它们之间放置空格(零或一)来构成。
我的解决方案如下:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
void permutationWithSpacesAux(const char* s, string buf, int s_index, int b_index, int len_s){
// stop condition
if(s_index == len_s){
cout << buf << endl;
return;
}
// print w\o space
buf[b_index] = s[s_index];
// recursive call w\ next indices
permutationWithSpacesAux(s, buf, s_index + 1, b_index + 1, len_s);
// print w\ space
buf[b_index] = ' ';
buf[b_index + 1] = s[s_index];
// recursive call w\ next indices
permutationWithSpacesAux(s, buf, s_index + 1, b_index + 2, len_s);
}
void permutationWithSpaces(const char* s){
int n = strlen(s);
string buf;
buf.reserve(2*n);
buf[0] = s[0];
permutationWithSpacesAux(s,buf, 1, 1,n);
}
int main() {
const char* s = "ABCD";
permutationWithSpaces(s);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
void permutationWithSpacesAux(const char* s, string buf, int s_index, int b_index, int len_s){
// stop condition
if(s_index == len_s){
cout << buf << endl;
return;
}
// print w\o space
buf[b_index] = s[s_index];
// recursive call w\ next indices
permutationWithSpacesAux(s, buf, s_index + 1, b_index + 1, len_s);
// print w\ space
buf[b_index] = ' ';
buf[b_index + 1] = s[s_index];
// recursive call w\ next indices
permutationWithSpacesAux(s, buf, s_index + 1, b_index + 2, len_s);
}
void permutationWithSpaces(const char* s){
int n = strlen(s);
string buf;
buf.reserve(2*n);
buf[0] = s[0];
permutationWithSpacesAux(s,buf, 1, 1,n);
}
int main() {
const char* s = "ABCD";
permutationWithSpaces(s);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的解决方案与指南的解决方案非常相似,只是我用于std::string缓冲区变量而不是char[]像指南那样。
我试图了解std::string该类的哪些属性可能会引发此问题。从我在网上找到的内容来看,我认为在尝试访问字符串字符时访问了内存中的非法位置,并且我认为问题出在我在内存中为buf.
我想更深入地了解这个问题,如果有人能进一步解释它的来源,我将不胜感激。
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |