leetcode - [917] Reverse Only Letters

2020/06/27

问题描述

Given a string S, return the “reversed” string where all characters that are not a letter stay in the same place, and all letters reverse their positions.

仅反转字符串中字母的顺序。

举个例子:

Example 1:
Input: "ab-cd"
Output: "dc-ba"

Example 2:
Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"

解法1

此题仍使用双指针思想。

我的想法是这样的:

首先,分别从头尾开始寻找第一个字母,否则跳过。

然后,两者互换,直至两个指针相遇。

来看下实现:

class Solution {
    public String reverseOnlyLetters(String S) {
        
        char[] arr = S.toCharArray();
        int lo = 0;
        int hi = arr.length - 1;
        
        while (lo < hi){
            while (lo < hi && !Character.isLetter(arr[lo])){
                lo++;
            }
            
            while (lo < hi && !Character.isLetter(arr[hi])){
                hi--;
            }
            
            if (lo < hi){
                char t  = arr[lo];
                arr[lo] = arr[hi];
                arr[hi] = t;
            }
            lo++;
            hi--;
        }
        
        return new String(arr);
    }
}

Enjoy it !


一位喜欢提问、尝试的程序员

(转载本站文章请注明作者和出处 姚屹晨-yaoyichen

Post Directory