[LeetCode force button] only reverse the letters, given a string S, return the "reversed" string, where the characters that are not letters are kept in place, and the positions of all letters are reversed

learning target:

Goal: proficiently use the knowledge learned in Java


Subject content:

The content of this article: Implemented in Java: Only reverse the letters


Title description:

Given a string S, return the "reversed" string, where the characters that are not letters are kept in place, and the positions of all letters are reversed.
Example 1:

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

Example 2:

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

Example 3:

Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"

Problem-solving ideas:

Change the topic only by swapping letters, so you can't just use the swap sequence to achieve it, but we only need to add two simple conditions.

Implementation code:

public class Practice_03 {
    
    
    public static void main(String[] args) {
    
    
        //给定一个字符串 S ,返回 “反转后的” 字符串,其中不是字母的字符都保留在原地,而所有字母的位置发生反转
        String str = "zh-sd)s";
        System.out.println(reverseOnlyLetters(str));
    }
        public static String reverseOnlyLetters(String S) {
    
    
            char[] arr=S.toCharArray();
            int i=0;//顺序遍历下标
            int j=S.length()-1;//逆序遍历下标
            while(i<j){
    
    
                while(i<j&&!isLetter(arr[i]))i++;//当i<j并且元素不是字母
                while(i<j&&!isLetter(arr[j])) j--;
                char temp;
                temp=arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
                i++;
                j--;
            }
            return new String(arr);
        }
    }

operation result:

sd-sh)z

Guess you like

Origin blog.csdn.net/zhangxxin/article/details/112996057