哈理工oj 1677
生活随笔
收集整理的這篇文章主要介紹了
哈理工oj 1677
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
水題,可我做了三小時。。。
題目大意就是在一個只含有‘x’和‘y’字符的字符串中,除掉所有‘xy’對(不分前后順序),不管‘x’和‘y’之間有沒有字符,只要能湊成一對就要除掉。
一開始我就看錯題意導致做了很久,后來發現,這不就是用棧搞定的題嘛。
思路:先用一個數組存下字符串,然后把字符串從頭到尾往棧里面塞字符,如果棧頂元素的字符與字符串中的字符不相同,就推出棧頂元素,同時字符串中的那個字符也不塞入棧中,最后再把棧中元素全部輸出即可。
代碼如下:
#include <iostream> #include <cstring> #include <cstdlib> #include <stack> #define maxn 1000006 using namespace std;char str[maxn] = {}; int main() {while(cin >> str){stack<char> book;int len = strlen(str);for(int i = 0; i < len; i++){if(book.empty()){book.push(str[i]);}else{if(book.top() == str[i]){book.push(str[i]);}else{book.pop();}}}while(!book.empty()){cout << book.top();book.pop();}cout << endl;memset(str, 0, sizeof(str));} }錯誤代碼:
#include <cstdio> #include <cstdlib> #include <cstring> #include <stack> #define maxn 1000006using namespace std;char str[maxn] = {}, rec[maxn] = {}; int main() {char ch;int cnt = 0;while(~scanf("%s", &str)){stack<char> book;int len = strlen(str);if(len == 1){printf("%s\n", str);continue;}for(int i = 0; i < len; i++){if(str[i] == 'x' && str[i + 1] == 'y'){i++;}else{book.push(str[i]);//printf("%c", str[i]);}}//printf("\n");int flag = 1;while(flag == 1){int cnt = 1;rec[1] = book.top();book.pop();flag = 0;printf("%c", rec[1]);while(!book.empty()){if(rec[cnt] != book.top()) flag = 1;if(rec[cnt] == 'x' && book.top() == 'y'){rec[cnt] = 0;book.pop();}else{cnt++;rec[cnt] = book.top();printf("%c", rec[cnt]);}if(!book.empty()) book.pop();}printf("\n*******\n");//printf("%d\n", book.empty());if(!flag) break;int len = strlen(rec + 1);printf("%d\n", len);for(int i = 1; i <= len; i++){printf("%c", rec[i]);book.push(rec[i]);rec[i] = 0;}printf("\n#########\n");}printf("%s\n", rec + 1);memset(str, 0, sizeof(str));memset(rec, 0, sizeof(rec));} } /** xyyxxx */?
總結
以上是生活随笔為你收集整理的哈理工oj 1677的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux最小安装桌面,Linux工作环
- 下一篇: 【视觉SLAM14讲】【汇总】