Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/917.html

917. Reverse Only Letters (Easy)

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 "

Companies:
Microsoft

Related Topics:
String

Solution 1.

  • class Solution {
        public String reverseOnlyLetters(String S) {
            char[] array = S.toCharArray();
            int low = 0, high = array.length - 1;
            while (low < high) {
                char c1 = array[low], c2 = array[high];
                if (Character.isLetter(c1) && Character.isLetter(c2)) {
                    array[low] = c2;
                    array[high] = c1;
                    low++;
                    high--;
                } else {
                    if (!Character.isLetter(c1))
                        low++;
                    if (!Character.isLetter(c2))
                        high--;
                }
            }
            return new String(array);
        }
    }
    
    ############
    
    class Solution {
        public String reverseOnlyLetters(String s) {
            char[] chars = s.toCharArray();
            int i = 0, j = s.length() - 1;
            while (i < j) {
                while (i < j && !Character.isLetter(chars[i])) {
                    ++i;
                }
                while (i < j && !Character.isLetter(chars[j])) {
                    --j;
                }
                if (i < j) {
                    char t = chars[i];
                    chars[i] = chars[j];
                    chars[j] = t;
                    ++i;
                    --j;
                }
            }
            return new String(chars);
        }
    }
    
  • // OJ: https://leetcode.com/problems/reverse-only-letters/
    // Time: O(N)
    // Space: O(1)
    class Solution {
    public:
        string reverseOnlyLetters(string S) {
            int i = 0, j = S.size() - 1;
            while (i < j) {
                while (i < j && !isalpha(S[i])) ++i;
                while (i < j && !isalpha(S[j])) --j;
                if (i < j) swap(S[i++], S[j--]);
            }
            return S;
        }
    };
    
  • class Solution:
        def reverseOnlyLetters(self, s: str) -> str:
            s = list(s)
            i, j = 0, len(s) - 1
            while i < j:
                while i < j and not s[i].isalpha():
                    i += 1
                while i < j and not s[j].isalpha():
                    j -= 1
                if i < j:
                    s[i], s[j] = s[j], s[i]
                    i, j = i + 1, j - 1
            return ''.join(s)
    
    ############
    
    class Solution(object):
        def reverseOnlyLetters(self, S):
            """
            :type S: str
            :rtype: str
            """
            letters = []
            N = len(S)
            for i, s in enumerate(S):
                if s.isalpha():
                    letters.append(s)
            res = ""
            for i, s in enumerate(S):
                if s.isalpha():
                    res += letters.pop()
                else:
                    res += s
            return res
    
  • func reverseOnlyLetters(s string) string {
    	ans := []rune(s)
    	i, j := 0, len(s)-1
    	for i < j {
    		for i < j && !unicode.IsLetter(ans[i]) {
    			i++
    		}
    		for i < j && !unicode.IsLetter(ans[j]) {
    			j--
    		}
    		if i < j {
    			ans[i], ans[j] = ans[j], ans[i]
    			i++
    			j--
    		}
    	}
    	return string(ans)
    }
    
    
  • function reverseOnlyLetters(s: string): string {
        const n = s.length;
        let i = 0,
            j = n - 1;
        let ans = [...s];
        while (i < j) {
            while (!/[a-zA-Z]/.test(ans[i]) && i < j) i++;
            while (!/[a-zA-Z]/.test(ans[j]) && i < j) j--;
            [ans[i], ans[j]] = [ans[j], ans[i]];
            i++;
            j--;
        }
        return ans.join('');
    }
    
    
  • impl Solution {
        pub fn reverse_only_letters(s: String) -> String {
            let mut cs: Vec<char> = s.chars().collect();
            let n = cs.len();
            let mut l = 0;
            let mut r = n - 1;
            while l < r {
                if !cs[l].is_ascii_alphabetic() {
                    l += 1;
                } else if !cs[r].is_ascii_alphabetic() {
                    r -= 1;
                } else {
                    cs.swap(l, r);
                    l += 1;
                    r -= 1;
                }
            }
            cs.iter().collect()
        }
    }
    
    

All Problems

All Solutions