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. [python]Generators

    generators(生成器)是python提供的一种机制,可以让函数一边循环一边计算,通常函数是一遍执行,而生成器可以在执行中间交出变量,下次调用时从交出变量的地方重新开始,这种机制通过yield关 ...

  2. python3编译安装no module named _ssl

    使用源码编译安装python3.6.7以后用pip 安装库, 出现如下问题 Retrying (Retry(total=4, connect=None, read=None, redirect=Non ...

  3. Maven项目中遇到的问题及其解决方案

    Maven中pom报红 1.jdk版本是否符合要求? 2.maven的本地confg中的setting.xml中是否和要求的jdk版本一致? 3.maven本地仓库路径是否正确,即为自己的确定的仓库位 ...

  4. Communication Model

    [Communication Model] EOSIO actions operate primarily in a message-based communication architecture. ...

  5. Java虚拟机 垃圾收集器与内存分配策略

    说起GC,我们要思考的主要有三件事 哪些内存需要回收 那些已经“死去”的对象,那么哪些对象“死”,哪些对象“活”呢,有个简单的办法 引用计数法,但是没法解决循环依赖问题 所以Java虚拟机采用的是可达 ...

  6. [leetcode]86. Partition List划分链表

    Given a linked list and a value x, partition it such that all nodes less than x come before nodes gr ...

  7. 每月最后一周的周六晚上21:00执行任务-crontab

    0 21 * * 6 /bin/sh /root/time.sh #“6”代表周六 时间判断脚本如下: #!/bin/bash if [ "$(date -d "+7 days&q ...

  8. python 之 函数

    什么是函数 引言 现在有这么个情况:假设我们python中的len方法不可以使用了,而恰好你又要计算一个字符串的长度你该怎么办呢?有人说:‘简单,可以使用for循环嘛 s1 = "hello ...

  9. 跑python用ThinkPad好还是MacBook好?

    跑Python,那肯定是服务器操作系统最好,找个方便安装Linux的本子. 我想题主的意图应该是做Python开发吧,如果是Python开发,还要看一下开发方向,如果是网络爬虫.服务器后端编程类的,那 ...

  10. 获取当前最顶层的ViewController

    - (UIViewController *)topViewController { UIViewController *resultVC; resultVC = [self _topViewContr ...