leetcode (Reverse Only Letters)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85226785

Title:Reverse Only Letters   917

Difficulty:Easy

原题leetcode地址: https://leetcode.com/problems/reverse-only-letters/

1.   双指针

时间复杂度:O(n),一次一层while循环。

空间复杂度:O(1),没有申请额外空间。

    /**
     * 双指针
     * @param S
     * @return
     */
    public static String reverseOnlyLetters(String S) {

        if (S.length() <= 0) {
            return S;
        }

        char cs[] = S.toCharArray();
        int start = 0;
        int end = S.length() - 1;

        while (start < end) {
            if (Character.isLetter(cs[start]) && Character.isLetter(cs[end])) {
                char c = cs[start];
                cs[start] = cs[end];
                cs[end] = c;
                start++;
                end--;
            }
            if (!Character.isLetter(cs[start])) {
                start++;
            }
            if (!Character.isLetter(cs[end])) {
                end--;
            }
        }

        return new String(cs);

    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/85226785
今日推荐