如果用戶輸入一個字串,我想創建一個函式來檢查是否重復一定數量的零跟隨相同數量的一。示例:001101(正確)、01(正確)、001010(錯誤)。我試圖將字串存盤在 2 個單獨的字串中并比較大小,但我的第二個 while 回圈沒有停止。
void check(string num) {
string st0 = "", st1 = "";
int n = num.length();
int k = 0;
while (k < n) {
int i = 0;
while (num[i] == num[i 1]) {
st0.push_back(num.back());
num.pop_back();
k ;
i ;
}
st0.push_back(num.back());
num.pop_back();
k ;
int j = 0;
while (num[j] == num[j 1]) {
st1.push_back(num.back());
num.pop_back();
k ;
j ;
}
st1.push_back(num.back());
num.pop_back();
k ;
if (st0.size() != st1.size()) {
cout << "incorrect \n";
}
st0.clear();
st1.clear();
}
}
uj5u.com熱心網友回復:
在這里,您從左到右測驗元素,并添加到字串中st0 的最后一個元素。num例如:
“111010”:在第一個 whilenum = "111"和st0 = "010"
while (num[i] == num[i 1]) {
st0.push_back(num.back());
num.pop_back();
k ;
i ;
}
要修復,您應該添加第一個測驗的元素而不是最后一個。
while( num[i] == num[i 1] && i 1 < n ){
st0.push_back(num[i]);
i ;
}
st0.push_back(num[i]);
i ;
你在這里犯了同樣的錯誤
while (num[j] == num[j 1]) {
st1.push_back(num.back());
num.pop_back();
k ;
j ;
}
使固定:
while( num[i] == num[i 1] && i 1 < n){
st1.push_back(num[i]); // same here
i ;
}
st1.push_back(num[i]);
i ;
我在這里使用了相同的方法i,以便我們繼續從我們在第一個 while 中中斷的地方回圈字串。
但是如果您有興趣,還有一個更優化的解決方案:
void check(string num)
{
int cnt0 = 0 , cnt1 = 0;
int n = num.length();
int i=0;
bool test = true ;
while (i<n){
/* we can use two variables and increment them instead of strings and compare them cauz we are not using the elements we just need the size of them */
while( num[i] == num[i 1] && i 1 < n ){
cnt0 ;
i ;
}
cnt0 ;
i ;
while( num[i] == num[i 1] && i 1 < n) {
cnt1 ;
i ;
}
cnt1 ;
i ;
if ( cnt1 != cnt0 ){
test = false ;
break;
}
cnt1 = 0;
cnt0 = 0;
}
if( test ) {
cout << "correct \n" ;
}
else {
cout << "incorrect \n" ;
}
}
如您所見,在上面的演算法中,您只需要字串的長度,st0因此st1您可以只使用 2 個 int 變數并測驗兩者之間的差異,這種方式記憶體效率更高,運行時間稍快。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520255.html
標籤:C 细绳
上一篇:如何從C中的字串中洗掉多個字符?
