I learn by doing, and enjoy using online judge sites to learn. Right now I am working on http://www.z-training.net/tasks.php?show_task=5000000406. Some of the test cases pass, but many get MLE/SEGF. My code is taking a brute force approach. Is this approach the cause of the MLE/SEGF error?
//z-last char
#include <iostream>
#include <string>
using namespace 开发者_StackOverflow社区std;
int main()
{
string str = "";
string tmp = "";
string newStr = "";
unsigned int strSize = 0;
unsigned int repeat;
unsigned int i;
int cnt = 0;
cin >> str;
cin >> repeat;
tmp = str;
strSize = str.size();
for (i=1;i<repeat;i++)
{
str += tmp;
strSize += strSize;
}
while (strSize > 1)
{
cnt = 0;
newStr = "";
for (i=1;i<strSize;i=i+2)
{
newStr += str[i];
cnt += 1;
}
//cout << newStr << endl;
strSize = cnt;
str = newStr;
}
cout << newStr << endl;
return 0;
}
I see a few problems here. In C and C++, arrays are numbered starting at 0 and end at allocated length - 1.
str[0]
refers to the first character in str
.
str[str.length() - 1]
refers to the last character in a str
.
Also, C strings are terminated with a binary 0. Some C++ string libraries keep their strings in C library format so the C string functions can be used on them. If you're disturbing the 0 at the end of the strings and the string library is trying to use a C string lib function that can also cause seg faults.
You're likely getting seg faults because you're reading or writing memory out of bounds.
精彩评论