zoukankan      html  css  js  c++  java
  • 917. Reverse Only Letters

    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"
    

    Example 3:

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

    Note:

    1. S.length <= 100
    2. 33 <= S[i].ASCIIcode <= 122 
    3. S doesn't contain  or "

    two pointers

    time: O(n), space: O(1)

    class Solution {
        public String reverseOnlyLetters(String S) {
            char[] str = S.toCharArray();
            int i = 0, j = str.length - 1;
            while(i < j) {
                if(Character.isLetter(str[i]) && Character.isLetter(str[j])) {
                    swap(str, i++, j--);
                } else if(Character.isLetter(str[i])) {
                    j--;
                } else if(Character.isLetter(str[j])) {
                    i++;
                } else {
                    i++;
                    j--;
                }
            }
            return new String(str);
        }
        
        private void swap(char[] arr, int i, int j) {
            char tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
        }
    }
  • 相关阅读:
    UE4 UnLoadStreamLevel
    UE4 Xml读写
    UE4 保存为bitmap
    C++ 不定参数(转)
    C++ 默认参数(转载)
    Tuple初探
    遗传算法matlab实现
    蚁群算法matlab实现
    汉诺塔问题C++实现
    较优H圈matlab实现
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11340658.html
Copyright © 2011-2022 走看看