String specifies character reversal

1 topic

A topic on Niuke.com.

Given two strings s1, s2, flip the characters in s1 contained in s2.

示例1
输入
"abcde","bcd"
输出
"adcbe"
说明
将'b','c','d'翻转 
示例2
输入
"acbde","dc"
输出
"adbce"
说明
将'c','d'翻转 

备注:
s1,s2只包含小写字母s1,s2只包含小写字母
1<=|s1|<=1e51<=∣s1∣<=1e5
1<=|s2|<=261<=∣s2∣<=26

链接:https://www.nowcoder.com/questionTerminal/fc0f14baa6b94f48bed7207f863db8d8
来源:牛客网

2 Ideas and source code

The description of the topic is not very clear, and the examples given are very misleading. At first I thought it was reversed according to s2. For example, in example 2, s2 = "bcd", so the reverse method of s1 is to transpose b and d, and the example given just satisfies this. But in fact, the meaning of the title is that the common characters of s1 and s2 contained in s1 are reversed in the order they appear in s1, and have nothing to do with the order of s2.

Let me talk about my thinking, traverse s1 from both ends to the middle, find the characters on the left and right in s2 respectively, and then swap them. The topic is actually very simple. Let me share with you my thinking, because I see that many answers use an extra stack, which I personally feel is unnecessary.

public String reverse (String s1, String s2) {
    
    
        // write code here
        int left = 0;
        int right = s1.length()-1;
        char[] s1Char = s1.toCharArray();
        while(left<right) {
    
    
            while (!s2.contains(String.valueOf(s1Char[left]))) {
    
    
                ++left;
            }
            while (!s2.contains(String.valueOf(s1Char[right]))) {
    
    
                --right;
            }
            char temp = s1Char[left];
            s1Char[left] = s1Char[right];
            s1Char[right] = temp;
            ++left;
            --right;
        }
        return String.valueOf(s1Char);
    }

Guess you like

Origin blog.csdn.net/hejnhong/article/details/124553674