To some string S, we will perform some replacement operations that replace groups of letters with new ones (not necessarily the same size).

Each replacement operation has 3 parameters: a starting index i, a source word x and a target word y.  The rule is that if x starts at position i in the original string S, then we will replace that occurrence of x with y.  If not, we do nothing.

For example, if we have S = "abcd" and we have some replacement operation i = 2, x = "cd", y = "ffff", then because "cd" starts at position 2 in the original string S, we will replace it with "ffff".

Using another example on S = "abcd", if we have both the replacement operation i = 0, x = "ab", y = "eee", as well as another replacement operation i = 2, x = "ec", y = "ffff", this second operation does nothing because in the original string S[2] = 'c', which doesn't match x[0] = 'e'.

All these operations occur simultaneously.  It's guaranteed that there won't be any overlap in replacement: for example, S = "abc", indexes = [0, 1], sources = ["ab","bc"] is not a valid test case.

Example 1:

Input: S = "abcd", indexes = [0,2], sources = ["a","cd"], targets = ["eee","ffff"]
Output: "eeebffff"
Explanation: "a" starts at index 0 in S, so it's replaced by "eee".
"cd" starts at index 2 in S, so it's replaced by "ffff".

Example 2:

Input: S = "abcd", indexes = [0,2], sources = ["ab","ec"], targets = ["eee","ffff"]
Output: "eeecd"
Explanation: "ab" starts at index 0 in S, so it's replaced by "eee".
"ec" doesn't starts at index 2 in the original S, so we do nothing.

Notes:

  1. 0 <= indexes.length = sources.length = targets.length <= 100
  2. 0 < indexes[i] < S.length <= 1000
  3. All characters in given inputs are lowercase letters.

Approach #1: String. [Java]

class Solution {
public String findReplaceString(String S, int[] indexes, String[] sources, String[] targets) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < indexes.length; ++i) {
if (S.startsWith(sources[i], indexes[i]))
map.put(indexes[i], i);
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < S.length(); ) {
if (map.containsKey(i)) {
sb.append(targets[map.get(i)]);
i += sources[map.get(i)].length();
} else {
sb.append(S.charAt(i));
i++;
}
}
return sb.toString();
}
}

  

Analysis:

Idea: Use a StringBuilder to build up the result.

1. Iterate through the indexes array and find out all indices that support replacement. Then, store mapping from those index values to their indices in the indexes array into a map named map.

2. Iterate through str, at each iteration i, check whether we can perform replacement, i.e., map.get(i) != null, if yes, append targets[i] to the StringBuilder and increase i by sources[i].length()-1. if no, append str.charAt(i) and increment i.

Reference:

https://leetcode.com/problems/find-and-replace-in-string/discuss/134758/Java-O(n)-solution

833. Find And Replace in String的更多相关文章

  1. 【LeetCode】833. Find And Replace in String 解题报告(Python)

    [LeetCode]833. Find And Replace in String 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu ...

  2. LC 833. Find And Replace in String

    To some string S, we will perform some replacement operations that replace groups of letters with ne ...

  3. 833. Find And Replace in String —— weekly contest 84

    Find And Replace in String To some string S, we will perform some replacement operations that replac ...

  4. String.replace与String.format

    字符串的替换函数replace平常使用的频率非常高,format函数通常用来填补占位符.下面简单总结一下这两个函数的用法. 一.String.replace的两种用法 replace的用法如:repl ...

  5. [转]String.Replace 和 String.ReplaceAll 的区别

    JAVA 中的 replace replaceAll 问题: 测试code System.out.println("1234567890abcdef -----> "+&qu ...

  6. Java: Replace a string from multiple replaced strings to multiple substitutes

    Provide helper methods to replace a string from multiple replaced strings to multiple substitutes im ...

  7. [LeetCode] Find And Replace in String 在字符串中查找和替换

    To some string S, we will perform some replacement operations that replace groups of letters with ne ...

  8. [Swift]LeetCode833. 字符串中的查找与替换 | Find And Replace in String

    To some string S, we will perform some replacement operations that replace groups of letters with ne ...

  9. JAVA中string.replace()和string.replaceAll()的区别及用法

    乍一看,字面上理解好像replace只替换第一个出现的字符(受javascript的影响),replaceall替换所有的字符,其实大不然,只是替换的用途不一样.    public String r ...

随机推荐

  1. leetcode101

    /** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNo ...

  2. java枚举类型

    jvm并不支持枚举类型,java中枚举类型是在编译器层面上实现的,先看如下代码: package demo.nio; public class EnumDemo { public static enu ...

  3. Microsoft DQS sqlException 0x80131904 - SetDataQualitySessionPhaseTwo

    遇到这个问题的原因可以从报错信息看出来,大概率是.net framework的问题 可以尝试如下解决途径 1. regenerate .net Assemble for DQS 2. 如果步骤一无法解 ...

  4. 吴裕雄 python深度学习与实践(8)

    import cv2 import numpy as np img = cv2.imread("G:\\MyLearning\\TensorFlow_deep_learn\\data\\le ...

  5. Django_models下划线__正反查询,对象正反查询

    1.我们使用models对数据库进行查询的时候,想去拿到结果的时候有时直接使用".字段",有时是'[0].字段',区别就是我们使用的语句返回的到底是一个对象还是列表: obj=mo ...

  6. mysql_day01

    1.MySQL概述 1.什么是数据库 数据库是一个存储数据的仓库 2.都有哪些公司在用数据库 金融机构.游戏网站.购物网站.论坛网站 ... ... 3.提供数据库服务的软件 1.软件分类 MySQL ...

  7. MQ队列堵塞无法读取经验总结

    问题现象: 1号发生本地来帐队列无法读取消息的问题,导致来帐报文均无法正常处理. 原因分析: 应用系统没有修改或上包,昨天交易和消息读取还是一切正常,mbfe的状态也是正常,mq的状态正常,以上正常可 ...

  8. 245. Shortest Word Distance III 单词可以重复的最短单词距离

    [抄题]: Given a list of words and two words word1 and word2, return the shortest distance between thes ...

  9. [leetcode]47. Permutations全排列(给定序列有重复元素)

    Given a collection of numbers that might contain duplicates, return all possible unique permutations ...

  10. python--事务操作

    #coding=utf-8 import sys import MySQLdb class TransferMoney(object): def __init__(self,conn): self.c ...