swdev
BAN USERvoid trimExcessSpace(string &orig) {
if (orig.length() == 0)
return;
int sIdx = 0, counter = 0;
bool hasSpace = false;
for (int i = 0; i < orig.length(); i++) {
if (orig[i] != ' ') {
counter++;
orig[sIdx++] = orig[i];
hasSpace = false;
} else if (!hasSpace) {
counter++;
orig[sIdx++] = orig[i];
hasSpace = true;
}
}
orig = orig.substr(0, counter);
}
string shiftLeft(const string &lhs, int shiftNum) {
if (shiftNum == 0) {
return lhs;
}
if (shiftNum < 0) {
return shiftRight(lhs, -shiftNum);
}
if (shiftNum >= lhs.length()) {
shiftNum = shiftNum - shiftNum / lhs.length();
}
string result = "";
for (int i = (int)(lhs.length() - 1 - shiftNum); i < lhs.length(); i++) {
result += lhs[i];
}
for (int i = 0; i < (lhs.length() - 1 - shiftNum); i++)
{
result += lhs[i];
}
return result;
}
string shiftRight(const string &lhs, int shiftNum) {
if (shiftNum == 0) {
return lhs;
}
if (shiftNum < 0) {
return shiftLeft(lhs, -shiftNum);
}
if (shiftNum >= lhs.length()) {
shiftNum = shiftNum - shiftNum / lhs.length();
}
string result = "";
result += lhs.substr(shiftNum, lhs.length() - shiftNum);
result += lhs.substr(0, shiftNum);
return result;
}
int replaceStr(string &orig, const string &from, const string &to) {
if (from == "")
return 0;
int count = 0;
string result = "";
int temp = 0;
int origIdx = 0;
string subStr = "";
for (int i = 0; i < orig.length(); ++i) {
if (i >= from.length()) {
subStr += orig[i - from.length()];
}
if (from[temp] == orig[i]) {
temp++;
}
if (temp >= from.length()) {
temp = 0;
// copyStr(orig, result, origIdx, i - (int)from.length() + 1);
result += subStr;
result += to;
origIdx = i + 1;
subStr = "";
count++;
}
}
for (int i = origIdx; i < orig.length(); ++i) {
result += orig[i];
}
cout << "orig str: " << orig << endl;
orig = result;
cout << "final str: " << orig << endl;
return count;
}
This algorithm does not work for the following example:
- swdev June 14, 2014k = 3;
input: WWWBBB
minimum configuration could be: WWW B BB => sum = 0
the algorithm above gives: WW WB BB => sum = 1