标签:
消除函数
string eliminate(string buffer) { string tmpbuff = buffer; int len; int len2; int index, start, end; bool isSame = false; end = 0; index = 0; len = buffer.length(); while (end < len) { /* 此时 start指向上一个以处理的字符,end指向下一个待处理的字符 */ start = end; end++; /* start已经是最后一个了 */ if (end == len) { buffer.at(index) = tmpbuff.at(start); index++; continue; } /* 2个相邻字符不一样 */ else if (tmpbuff.at(end) != tmpbuff.at(start)) { buffer.at(index) = tmpbuff.at(start); index++; continue; } /* 2个相邻字符一样 */ else { /* 找下一个不一样的字符 */ while((end != len) && (tmpbuff.at(start) == tmpbuff.at(end))) { end++; } } } buffer.resize(index); return buffer; }
最开始想的是,插入的字符一定要和前或者后的一样,结果发现一直有错。仔细想想,比如ACBCCCA的情况,应该在CC和C之间插入B。
int main(void) { int strNumber; int initialStrLength, ultimaStrLength; string strBuffer, tmpBuffer; string insertString= "ABC"; cin >> strNumber; cin.ignore(); for (int i = 0; i < strNumber; i++) { getline(cin, strBuffer); initialStrLength = strBuffer.length(); ultimaStrLength = initialStrLength; for (int j = 0; j < initialStrLength; j++) { tmpBuffer = strBuffer.substr(0,j + 1); tmpBuffer += strBuffer.substr(j, strBuffer.length() - j); int len = tmpBuffer.length(); tmpBuffer = eliminate(tmpBuffer); while (len > tmpBuffer.length()) { len = tmpBuffer.length(); tmpBuffer = eliminate(tmpBuffer); } if(ultimaStrLength > tmpBuffer.length()) { ultimaStrLength = tmpBuffer.length(); } } cout << initialStrLength - ultimaStrLength + 1 << endl; } return 0; }
标签:
原文地址:http://www.cnblogs.com/l00196472/p/4816951.html