LeetCode 833. 字符串中的查找与替换(排序,replace)
文章目錄
- 1. 題目
- 2. 解題
1. 題目
某個字符串 S 需要執行一些替換操作,用新的字母組替換原有的字母組(不一定大小相同)。
每個替換操作具有 3 個參數:起始索引 i,源字 x 和目標字 y。
規則是:如果 x 從原始字符串 S 中的位置 i 開始,那么就用 y 替換出現的 x。如果沒有,則什么都不做。
舉個例子,如果 S = “abcd” 并且替換操作 i = 2,x = “cd”,y = “ffff”,那么因為 “cd” 從原始字符串 S 中的位置 2 開始,所以用 “ffff” 替換它。
再來看 S = “abcd” 上的另一個例子,如果一個替換操作 i = 0,x = “ab”,y = “eee”,以及另一個替換操作 i = 2,x = “ec”,y = “ffff”,那么第二個操作將不會執行,因為原始字符串中 S[2] = 'c',與 x[0] = 'e' 不匹配。
所有這些操作同時發生。保證在替換時不會有任何重疊: S = "abc", indexes = [0, 1], sources = ["ab","bc"] 不是有效的測試用例。
示例 1: 輸入:S = "abcd", indexes = [0,2], sources = ["a","cd"], targets = ["eee","ffff"] 輸出:"eeebffff" 解釋: "a" 從 S 中的索引 0 開始,所以它被替換為 "eee"。 "cd" 從 S 中的索引 2 開始,所以它被替換為 "ffff"。示例 2: 輸入:S = "abcd", indexes = [0,2], sources = ["ab","ec"], targets = ["eee","ffff"] 輸出:"eeecd" 解釋: "ab" 從 S 中的索引 0 開始,所以它被替換為 "eee"。 "ec" 沒有從原始的 S 中的索引 2 開始,所以它沒有被替換。提示: 0 <= S.length <= 1000 S 僅由小寫英文字母組成 0 <= indexes.length <= 100 0 <= indexes[i] < S.length sources.length == indexes.length targets.length == indexes.length 1 <= sources[i].length, targets[i].length <= 50 sources[i] 和 targets[i] 僅由小寫英文字母組成來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/find-and-replace-in-string
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
字符串替換 http://www.cplusplus.com/reference/string/string/replace/
class Solution { public:string findReplaceString(string S, vector<int>& indexes, vector<string>& sources, vector<string>& targets) {int n = S.size(), i = 0, k, len;unordered_map<int,int> m;for(i = 0; i < indexes.size(); i++) {m[indexes[i]] = i;//原始數值 --> 對應的原始序號}sort(indexes.begin(), indexes.end());for(i = int(indexes.size())-1; i >= 0; i--){ //從大的序號開始替換,不需考慮序號變化k = m[indexes[i]];len = sources[k].size();if(S.substr(indexes[i], len) == sources[k]){S.replace(indexes[i], len, targets[k]);}}return S;} };8 ms 10.7 MB
我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的LeetCode 833. 字符串中的查找与替换(排序,replace)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 732. 我的日程安排
- 下一篇: LeetCode 489. 扫地机器人(