833-Find and replace in a string

Title description:

You'll get a string  s (indexed from 0) on which you have to perform  k a replace operation. The replacement operation  k is given as three parallel arrays of length: indicessources,   targets.

To complete the first  i replacement operation:

  1. Checks   if  substring   occurs at  index  in original string  .sources[i] sindices[i]
  2. If not present,  do nothing  .
  3. If present, replace  targets[i] the  substring with .

For example, if  s = "abcd" ,  indices[i] = 0 ,  sources[i] = "ab"targets[i] = "eee" , then the result of the substitution would be   ."eeecd"

All replacement operations must  happen concurrently , which means that replacement operations should not affect each other's indexes. Test cases ensure that elements do not overlap  .

  • For example,  a test case  for ,  s = "abc" will    not be generated because of  overlap  with   replacement.indices = [0,1]sources = ["ab","bc"]"ab""bc"

s Returns  the resulting string after  performing all replacement operations on the pair  .

A substring  is a contiguous sequence of characters in a string.

Example 1:

Input: s = "abcd", indices = [0,2], sources = ["a","cd"], targets = ["eee","ffff"] Output: "eeebffff" Explanation:
 " a
 "
 from s starts at index 0, so it is replaced with "eee". 
"cd" starts at index 2 in s, so it is replaced with "ffff".

Example 2:

Input: s = "abcd", indices = [0,2], sources = ["ab","ec"], targets = ["eee","ffff"] Output: "eeecd" Explanation:
 " ab
 "
 from s starts at index 0, so it is replaced with "eee". 
"ec" does not start at index 2 in the original S, so it is not replaced.

hint:

  • 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 Consists of lowercase English letters only
  • sources[i] and  targets[i] consist only of lowercase English letters

Problem-solving ideas:

Method 1: Sorting by subscript + simulation
Ideas and algorithms

We can directly simulate according to the requirements of the topic.

First, we sort all the replacement operations in ascending order according to the array indices\textit{indices}indices. In this step, it is difficult to sort the three arrays of indices\textit{indices}indices, sources\textit{sources}sources, targets\textit{targets}targets at the same time. We can use a length (denoted as mmm) and Their same array ops\textit{ops}ops stores the mmm subscripts from 000 to m−1m-1m−1, and then uses indices\textit{indices}indices as the first key for ops\textit{ops}ops itself Words can be sorted.

After the sorting is completed, we can traverse the given string sss for operation. We use another pointer pt\textit{pt}pt to point to the first element of ops\textit{ops}ops, indicating the current operation to be performed. When we traverse to the iiith character, we first keep moving pt\textit{pt}pt to the right until it moves out of the boundary, or ops[pt]\textit{ops}[\textit{pt}]ops[pt ] The subscript of the operation is not less than iii. At this point, there will be the following two situations:

If the subscript is greater than iii, it means that there is no operation with subscript iii. We can directly put character iii into the answer;

If this subscript is equal to iii, it means that there is an operation with subscript iii. We compare the length of sss starting from position iii with the substring of sources[ops[i]]\textit{sources}[\textit{ops}[i]]sources[ops[i]] and sources[ops[i]] \textit{sources}[\textit{ops}[i]]sources[ops[i]] for comparison:

If they are equal, then the replacement operation succeeded and we put targets[ops[i]]\textit{targets}[\textit{ops}[i]]targets[ops[i]] into the answer. Since the replacement operation cannot overlap, we can directly skip the number of characters of sources[ops[i]]\textit{sources}[\textit{ops}[i]]sources[ops[i]] length;

Otherwise, the substitution operation fails and we can simply put character iii into the answer.

It should be noted that the title only guarantees that successful replacement operations will not overlap, but does not guarantee that failed replacement operations will not overlap. Therefore, when this subscript is equal to iii, there may be multiple replacement operations that need to be tried, that is, we need to move ptptpt to the right until it moves out of the boundary, or ops[pt]\textit{ops}[\textit{pt }]ops[pt] ops with subscripts strictly greater than iii. The replacement operations traversed need to be tried in turn. If one of them succeeds, the rest do not need to be tried and can be exited directly.

the code

class Solution {
    public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {
        //定义n,m分别代表s字符串的长度和索引数组的长度
        int n = s.length(), m = indices.length;
        //用ArrayList ops来保存indices,作为对应s字符串下标值
        //利用ArrayList以便于排序等操作
        List<Integer> ops = new ArrayList<>();
        for (int i = 0; i < m; i++) {
            ops.add(i);
        }
        //??
        ops.sort((i, j) -> indices[i] - indices[j]);
        
        //利用StringBuilder保存结果
        StringBuilder ans = new StringBuilder();
        //??
        //>>>>>>>>>>>>>这是在准备下标值
        int pt = 0;
        for (int i = 0; i < n;) {
            while (pt < m && indices[ops.get(pt)] < i) {
                pt++;
            }
        //>>>>>>>>>>>>>>
            //初始化查找结果标记
            boolean succeed = false;
            //遍历条件1:下标的限制条件
            while (pt < m && indices[ops.get(pt)] == i) {
                //遍历条件2:字符串比较的条件
                if (s.substring(i, Math.min(i + sources[ops.get(pt)].length(), n)).equals(sources[ops.get(pt)])) {
                    //查找结果标记改变
                    succeed = true;
                    //相等则退出本次循环
                    break;
                }
                //循环下一个下标值
                pt++;
            }
            //本次查找完成后对应的操作
            if (succeed) {
                //有匹配的:需要进行使用目标字符串替换被查找的字符串的对应的字符
                ans.append(targets[ops.get(pt)]);
                i += sources[ops.get(pt)].length();
            } else {
                //没有匹配的:直接追加到结果尾部
                ans.append(s.charAt(i));
                i++;
            }
        }
        //返回结果字符串
        return ans.toString();

    }
}

Guess you like

Origin blog.csdn.net/haigand/article/details/132309853