題目描述
輸入兩個字串,從第一字串中刪除第二個字串中所有的字元。
例如,輸入」they are students.」和」aeiou」,則刪除之後的第乙個字串變成」thy r stdnts.」
輸入描述: 每個測試輸入包含2個字串
輸出描述: 輸出刪除後的字串
示例
輸入: they are students. aeiou解題思路輸出: thy r stdnts.
思路一:暴力查詢
使用傳統的暴力查詢方式,如判斷第乙個串的字元是否在第二個串中,在再挪動字元刪除這個字元 的方式,效率為o(n^2),效率太低,很難讓人滿意。
注意:不能用erase(),因為邊遍歷邊刪除會有錯誤
完整**:
#define _crt_secure_no_warnings 1
#include #include #include #include using namespace std;
int main()
}j++;
} }cout << s1 << endl;
system("pause");
return 0;
}
思路二:應用雜湊表
1.將第二個字串的字元都對映到乙個hashtable陣列中,用來判斷乙個字元在這個字串。
2. 判斷乙個字元在第二個字串,不要使用刪除,這樣效率太低,因為每次刪除都伴隨資料挪動。這裡可 以考慮使用將不在字元新增到乙個新字串,最後返回新字串
完整**:
#define _crt_secure_no_warnings 1
#include #include #include #include using namespace std;
int main()
; //使用雜湊對映統計出現的字元
for (size_t i = 0; i < s2.size(); ++i)
hashtable[s2[i]]++;
//遍歷s1,沒出現在雜湊表中的字元都新增在s中
string s;
for (size_t i = 0; i < s1.size(); ++i)
cout << s;
system("pause");
return 0;
}
記得關注博主喲~ 牛客網 刪除公共字元
輸入兩個字串,從第一字串中刪除第二個字串中所有的字元。例如,輸入 they are students.和 aeiou 則刪除之後的第乙個字串變成 thy r stdnts.每個測試輸入包含2個字串輸出刪除後的字串示例1 they are students.aeiou thy r stdnts.思路 ...
牛客網 刪除公共字元三種解法
題目描述 輸入兩個字串,從第一字串中刪除第二個字串中所有的字元。例如,輸入 they are students.和 aeiou 則刪除之後的第乙個字串變成 thy r stdnts.輸入描述 每個測試輸入包含2個字串 輸出描述 輸出刪除後的字串 示例1 輸入 they are students.ae...
牛客網 刪除重複字元
一.題目 牛牛有乙個由小寫字母組成的字串s,在s中可能有一些字母重複出現。比如在 banana 中,字母 a 和字母 n 分別出現了三次和兩次。但是牛牛不喜歡重複。對於同乙個字母,他只想保留第一次出現並刪除掉後面出現的字母。請幫助牛牛完成對s的操作。二.解題思路 從字串中取出乙個元素,將這個元素和之...