文章目录
- Find And Replace in String 字符串中的查找与替换
- 问题描述:
- 分析
- 代码
- 线性模拟
- Tag
Find And Replace in String 字符串中的查找与替换
问题描述:
你会得到一个字符串 s
(索引从 0 开始),你必须对它执行 k
个替换操作。替换操作以三个长度均为 k
的并行数组给出:indices
, sources
, targets
。
要完成第 i
个替换操作:
- 检查 子字符串
sources[i]
是否出现在 原字符串s
的索引indices[i]
处。 - 如果没有出现, 什么也不做 。
- 如果出现,则用
targets[i]
替换 该子字符串。
例如,如果 s = "abcd"
, indices[i] = 0
, sources[i] = "ab"
, targets[i] = "eee"
,那么替换的结果将是 "eeecd"
。
所有替换操作必须 同时 发生,这意味着替换操作不应该影响彼此的索引。测试用例保证元素间不会重叠 。
- 例如,一个
s = "abc"
,indices = [0,1]
,sources = ["ab","bc"]
的测试用例将不会生成,因为"ab"
和"bc"
替换重叠。
在对 s
执行所有替换操作后返回 结果字符串 。
子字符串 是字符串中连续的字符序列。
1 < = s . l e n g t h < = 1000 k = = i n d i c e s . l e n g t h = = s o u r c e s . l e n g t h = = t a r g e t s . l e n g t h 1 < = k < = 100 0 < = i n d i c e s [ i ] < s . l e n g t h 1 < = s o u r c e s [ i ] . l e n g t h , t a r g e t s [ i ] . l e n g t h < = 50 s 仅由小写英文字母组成 s o u r c e s [ i ] 和 t a r g e t s [ i ] 仅由小写英文字母组成 1 <= s.length <= 1000\\ k == indices.length == sources.length == targets.length\\ 1 <= k <= 100\\ 0 <= indices[i] < s.length\\ 1 <= sources[i].length, targets[i].length <= 50\\ s 仅由小写英文字母组成\\ sources[i] 和 targets[i] 仅由小写英文字母组成 1<=s.length<=1000k==indices.length==sources.length==targets.length1<=k<=1000<=indices[i]<s.length1<=sources[i].length,targets[i].length<=50s仅由小写英文字母组成sources[i]和targets[i]仅由小写英文字母组成
分析
之前的是基于有序的状态下,依次遍历每个被操作的字符串的每个位置,所以需要预处理排序。
而线性的思路,与其说是不排序,不如理解为利用数组的自己的有序性 ,避免了排序。
思路
其主要的思路是构建一个长度与原字符串等长的标记数组,然后遍历每个被操作的索引,并且进行验证。
-
如果需要替换,那么就把需要替换的目标串放入,并且记录其影响的位置长度。
-
如果不需要替换,同样进行标记,该位置的字符串默认直接插入结果串。
需要注意的是在发生替换的情况下,可能会对后续的一定长度的字符跳过。
代码
线性模拟
class Solution {public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {int n = s.length();var replaceStr = new String[n]; // 替换后的字符串var replaceLen = new int[n]; // 被替换的长度Arrays.fill(replaceLen, 1); // 无需替换时 i+=1for (int i = 0; i < indices.length; i++) {int idx = indices[i];if (s.startsWith(sources[i], idx)) {replaceStr[idx] = targets[i];replaceLen[idx] = sources[i].length();}}var ans = new StringBuilder();for (int i = 0; i < n; i += replaceLen[i]) { // 无需替换时 i+=1if (replaceStr[i] == null) {ans.append(s.charAt(i));} else {ans.append(replaceStr[i]);}}return ans.toString();}
}
时间复杂度 O ( L ) O(L ) O(L)
空间复杂度 O ( L ) O(L) O(L)
线性代码来源于灵神大佬
Tag
Array
Sort
String