1. 程式人生 > >LeetCode:917. Reverse Only Letters(反轉一個字串)

LeetCode: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 "

首先,這個題目是按照要求對字串進行交換位置,剛開始時候 ,我按照字串切割的方式,去切割字串,然後把字串擺到相應的位置,這個方式是可以做出來 ,但是出現了很多的臨界值的問題,後來放棄了這個做法,該用雙指標;

雙指標解法1:

 private String reverseOnlyLetters1(String S) {
        if (S.length() <= 1) {
            return S;
        }
        char[] chs = S.toCharArray();
        int i = 0;
        int j = chs.length - 1;
        while (i < j) {
            if (Character.isLetter(chs[i]) && Character.isLetter(chs[j])) {
                swap(chs,i,j);
                i++;
                j--;
            } else if (Character.isLetter(chs[i]) || Character.isLetter(chs[j])) {
                if (Character.isLetter(chs[i])) {
                    j--;
                } else {
                    i++;
                }

            } else {
                i++;
                j--;
            }
        }
        return String.valueOf(chs);
    }
    private void swap(char[] chs, int i, int j) {
        char temp = chs[i];
        chs[i] = chs[j];
        chs[j] = temp;
    }

 時間複雜度:O(n)

空間複雜度:O(1)


雙指標簡便方式解法2:

public class ReverseOnlyLetter917Four {
    @Test
    public void fun() {
        String s = "Test1ng-Leet=code-Q!";
        String newString = reverseOnlyLetters1(s);
        System.out.println(newString);
    }
    
    // 對字串進行反轉,除了字串之外的字元不變
    private String reverseOnlyLetters1(String S) {
        if (S.length() <= 1) {
            return S;
        }
        char[] chs = S.toCharArray();
        int i = 0;
        int j = chs.length - 1;
        while (i < j) {
            if (!Character.isLetter(chs[i])) {
                i++;
            } else if (!Character.isLetter(chs[j])) {
                j--;
            } else {
                swap(chs, i, j);
                i++;
                j--;
            }
        }
        return String.valueOf(chs);
    }

    // 交換兩個字元的位置
    private void swap(char[] chs, int i, int j) {
        char temp = chs[i];
        chs[i] = chs[j];
        chs[j] = temp;
    }
}

時間複雜度:O(n)

空間複雜度:O(1)