Leetcode Note: Go - Reverse Only Letters

Reverse Only Letters - LeetCode
https://leetcode.com/problems/reverse-only-letters/

  • Go 言語で取り組んだメモ

所感

  • string s で受け取った値をルールに則って反転して return する
  • ルール
    • English latters 以外は同じ位置を保持
    • English Letters は反転する

回答

Reverse Only Letters - LeetCode
https://leetcode.com/problems/reverse-only-letters/solution/

[GO] Solution Two pointers - LeetCode Discuss
https://leetcode.com/problems/reverse-only-letters/discuss/561821/GO-Solution-Two-pointers

func reverseOnlyLetters(S string) string {
    s := []byte(S)
    i,j := 0, len(S) - 1
    for i < j {
        for i < j && !isLetter(s[i]){
            i++
        }
        for i < j && !isLetter(s[j]){
            j--
        }
        s[i], s[j] = s[j], s[i]
        i++
        j--
    }
    
    return string(s)
}


func isLetter(b byte) bool {
	return 'a' <= b && b <= 'z' ||
		'A' <= b && b <= 'Z'
}