2017-07-11 39 views
0

希爾有一個字符串S,由N個小寫英文字母組成。在一個操作中,他可以刪除任何具有相同值的相鄰字母。例如,字符串「aabcc」在操作後將變成「aab」或「bcc」。減少字符串時,它有一對

希爾希望儘可能地減少S.要做到這一點,他會盡可能多地重複上述操作。通過查找和打印不可縮減的表格來幫助您隱藏!

如果最後的字符串爲空,則輸出空字符串;否則,打印最終的非還原字符串。

採樣輸入0

aaabccddd

樣本輸出0

ABD

採樣輸入1

BAAB

樣本輸出1

空字符串

採樣輸入2

AA

樣本輸出2

空字符串 說明

樣品箱0:SHIL可以執行以下的操作順序,以獲得最終字符串:

因此,我們打印t。

樣本案例1:SHIL可以執行以下的操作順序,以獲得最終的字符串:aaabccddd - > abccddd

abccddd - > abddd

abddd - > ABD

因此我們打印ABD

樣例1:baab - > bb

bb - >空字符串。

在我的while循環代碼中,當我將s [i]賦給str [i] .s [i]的值沒有被賦值給str [i]。str [i]有一個垃圾值。

我的代碼:

 int main() { 
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
    string s; 
cin>>s; 
int len = s.length(); 
int len1 = 0; 
string str; 
for(int i = 0;i < len-1;i++){ 
    if(s[i]!= '*'){ 
     for(int j=i+1;j < len;j++){ 
      if(s[j] != '*'){ 
       if(s[i] == s[j]){ 
        s[i] = s[j] = '*'; 
       } 
      } 
     } 
    } 
} 
int i = 0; 
while(i<len){ 
    if(s[i] != '*'){ 
     str[len1] = s[i]; 
     len1++; 

    } 
    i++; 
} 


if(len1 != 0){ 
    cout<<str; 

} 
else{ 
    cout<<"Empty String"; 
} 
return 0; 

}

+0

似乎不明確。 「儘可能多地做它」意味着什麼?剛剛遇到第一對時你會重新開始嗎? – erip

回答

0
#include <iostream> 
using namespace std; 

int main(){ 

string s,tempS; 
bool condition = false; 
cin >> s; 
tempS = s; 
while(condition==false){ 
    for(int i=1; i<s.size(); i++){ 
     if(s[i]==s[i-1]){ 
      s.erase(s.begin()+i-1, s.begin()+i+1); 
     } 
    } 
    if(tempS == s){ 
     condition = true; 
    } else{ 
     tempS = s; 
    } 
} 

if(s.size()==0){ 
    cout << "Empty String" ; 
} else{ 
    cout << s; 
} 

return 0; 
} 

第一while循環不斷修改串,直至和除非它變成等於溫度(其等於字符串預修改) 它比較相鄰的元素是否相等,然後刪除它們。 只要字符串在修改後變成等於temp,字符串就達到了最簡化的狀態!

+0

僅有代碼的答案沒有幫助。請包括一段強調代碼或使用的邏輯的段落。 –