leetcode 833. Find And Replace in String 题解

Android 13 GMS认证避坑:手把手教你搞定RKP配置,解决GTS测试fail 本文详细解析Android 13 GMS认证中的RKP(远程密钥配置)全流程,提供GTS测试失败的深度解决方案。从RKP核心概念到实战配置技巧,帮助开发者规避常见陷阱,确保设备顺利通过Google安全认证,特别适合需要快速掌握Android13 GMS认证的工程师参考。 阅读详情

833. Find And Replace in String

题目:

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.
题解:

将indexes按逆序排序,然后对S从右往左依次查找可替换的单词,如果出现在指定位置,则替换。由于indexes排序后,会变化,因此需要用map结构保存原来的索引。

技巧:
  1. 将indexes按逆序排序;
  2. 对字符串从右往左处理;
C++
class Solution {
public:
    string findReplaceString(string S, vector<int>& indexes, vector<string>& sources, vector<string>& targets) {
        vector<pair<int, int>> vp;
        int n = indexes.size();
        for(int i = 0; i < n; i++) {
            vp.push_back(make_pair(indexes[i], i));
        }

        // sort(vp.rbegin(), vp.rend());//对出现位置按逆序排序
        for(int i = 0; i < n; i++) {
            int pos = vp[i].first; // 指定的位置
            int ind = vp[i].second;// 要替换的单词的索引
            if(S.find(sources[ind], pos) == pos) {//如果sources[ind]出现在指定位置,则替换
                S = S.substr(0, pos) + targets[ind] + S.substr(pos+sources[ind].length());
            }
        }
        return S;
    }
};
Java
class Solution {
    public String findReplaceString(String S, int[] indexes, String[] sources, String[] targets) {
        Map<Integer, Integer> map = new HashMap<>();
        List<Integer> indList =new ArrayList<>();
        int n = indexes.length;
        for(int i = 0; i < n; i++) {
            map.put(indexes[i], i);
            indList.add(indexes[i]);
        }

        Collections.sort(indList);

        for(int i = n - 1; i >= 0; i--) {// 从右往左替换
            int pos = indList.get(i);
            int curInd = map.get(pos);
            if(S.indexOf(sources[curInd], pos) == pos) {// 检查sources[curInd]是否出现在指定pos,如果出现,则替换
                S = S.substring(0, pos) + targets[curInd] + S.substring(pos + sources[curInd].length());
            }
        }

        return S;     
    }
}
Python
class Solution(object):
    def findReplaceString(self, S, indexes, sources, targets):
        """
        :type S: str
        :type indexes: List[int]
        :type sources: List[str]
        :type targets: List[str]
        :rtype: str
        """
        dic = dict([])
        n = len(indexes)
        for i in range(n):
            dic[indexes[i]] = i 
        indexes.sort()
        j = n - 1
        while j >= 0:  # 从右往左替换
            pos = indexes[j]
            ind = dic[pos]
            if(S.find(sources[ind], pos) == pos): # //如果sources[ind]出现在指定位置,则替换
                S = S[0:pos] + targets[ind] + S[pos+len(sources[ind]):] 
            j -= 1
        return S
JavaScript
/**
 * @param {string} S
 * @param {number[]} indexes
 * @param {string[]} sources
 * @param {string[]} targets
 * @return {string}
 */
var findReplaceString = function(S, indexes, sources, targets) {
    var n = indexes.length;
    var map = new Map();
    for(let i = 0; i < n; i++) {
        map.set(indexes[i], i);
    }
    indexes.sort(function(x, y) { //对出现位置按逆序排序
        if(x < y) {
            return 1;
        }
        else if(x > y) {
            return -1;
        }
        return 0;
    });

    for(let i = 0; i < n; i++) {// 从右往左替换
        var pos = indexes[i];
        var ind = map.get(pos);
        if(S.indexOf(sources[ind], pos) == pos) {// 如果sources[ind]出现在指定位置,则替换
            S = S.substring(0, pos) + targets[ind] + S.substring(pos+ sources[ind].length);
        }
    }
    return S;  
};
信号处理仿真:自适应信号处理_(8).自适应信道均衡 在无线通信系统中,信道的多径效应和时变特性会导致信号的失真,从而影响通信质量。自适应信道均衡技术通过实时调整均衡器的参数,以补偿信道失真,提高信号的质量和可靠性。本节将详细介绍自适应信道均衡的原理、算法和实现方法,并通过具体的仿真例子来说明其应用。 阅读详情

相关推荐

Windows显卡TDR超时导致Unity崩溃?手把手教你修改注册表延长响应时间

本文详细解析了Windows显卡TDR超时导致Unity崩溃的问题,并提供了修改注册表延长响应时间的完整解决方案。通过调整TdrDelay和TdrDdiDelay键值,开发者可以有效避免D3D11设备丢失错误,提升Unity编辑器的稳定性。文章还包含显卡驱动优化、系统性能调优等实用技巧,帮助开发者彻底解决编辑器崩溃问题。

weixin_33737774的博客 622

[leetcode] 890. Find and Replace Pattern

Description You have a list of words and a pattern, and you want to know which words in words matches the pattern. A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get

Learning from the mistakes 334

ad新版本学习笔记(基本包含一套流程)Altium Designer(ad20/ad21/ad22/ad23)

ad20-ad23学习笔记,逐渐补全

安和的博客 4万+

890. 查找和替换模式( Find and Replace Pattern) - leetcode简单题解

890. 查找和替换模式 描述 &amp;amp;nbsp;&amp;amp;nbsp;你有一个单词列表 words 和一个模式 pattern,你想知道 words 中的哪些单词与模式匹配。 &amp;amp;nbsp;&amp;amp;nbsp;如果存在字母的排列 p ,使得将模式中的每个字母 x 替换为 p(x) 之后,我们就得到了所需的单词,那么单词与模式是匹配的。(回想一下,字母的排列是从字母到字母的双射:每个字母映射到另一个字母,没有两个字...

Welcome ! This is Guanpx's blog. 688

Enterprise Architect 中文经典教程

本文使用到的EA工程文件下载 一、Enterprise Architect简介 Enterprise Architect是一个对于软件系统开发有着极好支持的CASE软件(Computer Aided Software Engineering)。EA不同于普通的UML画图工具(如VISIO),它将支撑系统开发的全过程。在需求分析阶段,系统分析与设计阶段,系统开发及部署等方面有着强大的支持,...

2万+

adams案例分析_案例1(麦弗逊悬架子系统创建)

本文字数3292字83图,建议阅读时间26分钟首先看下案例1的麦弗逊悬架数模结构就不细讲了,从数模上主要是获取硬点坐标(铰接点、安装点、参考点)及大部件结构(副车架、摆臂、转向节等实际运动过程中会产生变形的部件,在ADAMS Car中我们就可以用柔性体来搭建)再来回顾下上一篇讲到的模型元素1、Hardpoint——硬点(只有位置没有方向)2、Parameter Variable——参数...

weixin_39609407的博客 6476

leetcode--833. 字符串中的查找与替换[1]

https://leetcode-cn.com/problems/find-and-replace-in-string/description/ 对于某些字符串 S,我们将执行一些替换操作,用新的字母组替换原有的字母组(不一定大小相同)。 每个替换操作具有 3 个参数:起始索引 i,源字 x 和目标字 y。规则是如果 x 从原始字符串 S 中的位置 i 开始,那么我们将用 y替换出现的 x。如...

lattice的博客 712

STM32F429移植LVGL9.3.0:从源码配置到双缓冲优化实战

本文详细介绍了如何在STM32F429平台上移植LVGL 9.3.0图形库,涵盖从源码准备、工程配置、显示驱动适配到双缓冲优化等关键步骤。重点解析了利用STM32F429的硬件特性实现高效内存管理和流畅显示性能的实战技巧,为嵌入式GUI开发提供完整解决方案。

q6r7s8t9的博客 1133

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

【LeetCode】8833. Find And Replace in String 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/find...

负雪明烛 2158

电网加密芯片全解析:分类与功能​

在电网数字化转型的浪潮中,数据安全和设备的身份认证变得愈发重要。加密芯片作为保障电网信息安全的核心部件,凭借独特的技术特性,在不同应用场景下发挥着关键作用,有力推动着智能电网的安全稳定发展。接下来,我们将对电网中常见的加密芯片展开分类介绍,并探讨其对应的功能。​。

1962

【WB32库开发】第9章 TIM1高级定时器——输出多路PWM

PWM(Pulse Width Modulation)意为脉冲宽度调制,简称脉宽调制 。在工控行业,PWM信号可以用来调节电机转速、调节变频器以及BLDC电机驱动等;在LED照明行业,可以通过PWM来控制LED的亮暗变化;还可以通过PWM信号来控制无源蜂鸣器发出简单的声音等。 WB32也可输出PWM,需配置WB32上的定时器。 在WB32中有4个定时器,其中TIM1为高级定时器,TIMx(2-4)为通用定时器,这四个定时器均挂载在APB1总线上,每个定时器都可以输出4路PWM。 本章需要使用固件库TIM例程

北海村夫的博客 4637

LeetCode 833 Find And Replace in String

LeetCode 833 Find And Replace in String Problem Description: 题目给出四个已知条件:进行操作的字符串S,indexes数组(存储S中需进行替换的位置下标),sources数组(需要匹配S中有indexes数组中下标的子字符串是否与sources中对应子字符串相同),targets数组(如果匹配成功,将S中有indexes数组中下标...

萤火虫啊飞呀飞 1234

FPGA打砖块游戏设计(有上板照片)VHDL

这是一款经典打砖块游戏,我们的努力让它更精致更好玩,我们将它取名为打砖块游戏(Flyball),以下是该系统的一些基本功能: 画面简约而经典,色彩绚丽而活泼,动画流畅 玩家顺序挑战3个不同难度的级别,趣味十足 计分功能,卡通字母数字 4条生命值,由生命条显示 游戏结束画面,缓缓浮起与缤纷刷色的特效 四键操作,可复位,可暂停,高灵敏 96块砖拼出可爱的“囧”字,方便更改 碰挡板非镜面反射 初始启动,随机的发射速度。

QQ_778132974的博客 1661

进程间通信六大方式详解:从原理到高并发面试实战

在多线程与高并发开发中,线程间的数据共享相对直接,但进程间通信(IPC)却因地址空间隔离而成为工程与面试中的硬骨头。理解IPC的底层原理,是设计可靠多进程架构、完成服务拆分与消息流转的关键。管道提供最简单的字节流传递,消息队列实现带边界的异步解耦,共享内存凭借零拷贝成为性能之王,信号量负责并发控制,信号用于异步通知,Socket则突破单机限制。不同方案在数据量、同步性与通信范围上各有取舍。掌握这些技术的适用场景与潜在风险,不仅能帮你构建高性能系统,也能在面试中从容应对高并发项目的深层次追问,真正将线程、进程

weixin_34344403的博客 308

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

LeetCode //C - 833. Find And Replace in String

This problem involves performing multiple string replacements in a given string s based on specified indices, source, and target strings. The solution checks each source string at its given index in s and replaces it with the corresponding target string if

Made in Code 898

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

833. Find And Replace in String**

833. Find And Replace in String** https://leetcode.com/problems/find-and-replace-in-string/ 题目描述 To some string S, we will perform some replacement operations that replace groups of letters with new o...

珍妮的选择的博客 414

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

[leetcode] 833. Find And Replace in String

Description 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 s...

Learning from the mistakes 203

LeetCode #833 - Find And Replace in String

题目描述: 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 start...

LawFile的博客 264

Leetcode 833. Find And Replace in String

文章作者:Tyan 博客:noahsnail.com  |  优快云  |  简书 1. Description 2. Solution **解析:**Version 1,先排序,根据索引排序,对源字符串和目标字符串也根据索引的排序顺序排序,这样做主要为了判断是否有重叠字符串。遍历所有索引,如果当前索引加上源字符串的长度与下一个索引重叠,则当前索引以及下一个索引对应的字符串都不能替换。如果字符串s根据索引对应的字串与源字符串相等,则替换对应的子串,由于需要同时替换

SnailTyan 220

LeetCode in C++ 833. Find And Replace in String

To some string S, we will perform somereplacementoperations that replace groups of letters with new ones (not necessarily the same size). Each replacement operation has 3 parameters: a startin...

weixin_30457065的博客 115

833. Find And Replace in String

To some stringS, we will perform somereplacementoperations that replace groups of letters with new ones (not necessarily the same size). Each replacement operation has3parameters: a starting i...

weixin_30861459的博客 91

【Leetcode】833. Find And Replace in String

题目地址: https://leetcode.com/problems/find-and-replace-in-string/ 给定一个长nnn字符串sss,再给定一个非负整数数组ddd,和两个字符串数组SSS和TTT,要求对每个iii,将sss中下标从d[i]d[i]d[i]开始且与S[i]S[i]S[i]匹配的子串换成T[i]T[i]T[i],如果不匹配就不用换了。题目保证替换的区间没有重合,并且下标都合法。 按定义做就行,先将每个下标d[i]d[i]d[i]和其对应的S[i]S[i]S[i]和T[i]

数学、算法爱好者的博客 202

833.Find And Replace in String

class Solution { public: string findReplaceString(string S, vector<int>& indexes, vector<string>& sources, vector<string>& targets) { string strret; ...

就是那个党伟 197

LeetCode 833. Find And Replace in String【字符串,哈希表,模拟】1460

本文属于「征服LeetCode」系列文章之一,这一系列正式开始于2021/08/12。由于LeetCode上部分题目有锁,本系列将至少持续到刷完所有无锁题之日为止;由于LeetCode还在不断地创建新题,本系列的终止日期可能是永远。在这一系列刷题文章中,我不仅会讲解多种解题思路及其优化,还会用多种编程语言实现题解,涉及到通用解法时更将归纳总结出相应的算法模板。。

memcpy0的博客 320

leetcode 833. Find And Replace in String 字符串中的查找与替换

官方题解是先提取出所有匹配的,最后拼起来

邹九的个人博客 258

LeetCode每日一题(833. Find And Replace in String)

单纯动手的题, 好想,不好实现。首先将 indices、sources、targets 组合起来进行排序, 然后遍历 s, 遇到 indices 里的 index 就检查是否符合 source, 如果符合则往答案中 push target, 并且 i += source.len(), 如果不符合则 push current_char, i += 1。注意各种数组越界检查。

wangjun861205的博客 228
上一篇: leetcode 686. Repeated String Match 题解
下一篇: leetcode 125. Valid Palindrome 题解
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值