1. 程式人生 > 其它 >位元組真題:萬萬沒想到之聰明的編輯

位元組真題:萬萬沒想到之聰明的編輯

牛客連結:https://www.nowcoder.com/question/next?pid=16516564&qid=362292&tid=49703321

我叫王大錘,是一家出版社的編輯。我負責校對投稿來的英文稿件,這份工作非常煩人,因為每天都要去修正無數的拼寫錯誤。但是,優秀的人總能在平凡的工作中發現真理。我發現一個發現拼寫錯誤的捷徑: 1. 三個同樣的字母連在一起,一定是拼寫錯誤,去掉一個的就好啦:比如 helllo -> hello 2. 兩對一樣的字母(AABB型)連在一起,一定是拼寫錯誤,去掉第二對的一個字母就好啦:比如 helloo -> hello 3. 上面的規則優先“從左到右”匹配,即如果是AABBCC,雖然AABB和BBCC都是錯誤拼寫,應該優先考慮修復AABB,結果為AABCC

解題思路:比較簡單,一個佇列記錄結果,另外用兩個變數判斷當前元素是否加入佇列,但也用了40分鐘,一開始沒想清楚,用棧去了,,,qaq

#include<iostream>
#include<queue>
#include<vector>
using namespace std;

string getAloneRes(string init) {
    string res;
    if (init.size() == 0) return res;
    queue<char> sque;
    string::iterator it = init.begin();
    sque.push(*it);
    int pre_idx = 0, cur_idx = 1
; for (++it; it != init.end(); ++it) { if (sque.back() == *it) { // 和隊尾元素相同 /*if (pre_idx == 2 && cur_idx == 1) { continue; } else if (cur_idx == 2) { continue; }*/ // 11oo 和 111可以合併為一個判斷 if
(pre_idx == 2 || cur_idx == 2) continue; else { cur_idx++;sque.push(*it); } } else { // 和棧頂元素不同 pre_idx = cur_idx; cur_idx = 1; sque.push(*it); } } // 將得到的結果出棧(佇列啊) while (!sque.empty()) { res += sque.front();sque.pop(); } return res; } vector<string> getRes(int n, vector<string> init) { vector<string> res; int str_count = 0; // 正在處理第幾個字串 while (str_count < n) { res.push_back(getAloneRes(init[str_count++])); } return res; } int main() { int n; cin >> n; vector<string> init; for (int i = 0; i < n; ++i) { string tmp; cin >> tmp; init.push_back(tmp); } vector<string> res = getRes(n, init); for (int i = 0; i < n; ++i) { cout << res[i] << endl; } return 0; }
心之所願,永不相忘