Leetcode Note: Go - Remove All Adjacent Duplicates in String

Remove All Adjacent Duplicates In String - LeetCode
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/

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

回答

🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line (C++ / Python / Java / Go / Kotlin / Rust) - LeetCode Discuss
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/discuss/2798136/LeetCode-The-Hard-Way-Explained-Line-By-Line-(C%2B%2B-Python-Java-Go-Kotlin-Rust)

func removeDuplicates(s string) string {
    ans := make([]rune, 0, len(s))
    for _, c := range s {
        if len(ans) > 0 && ans[len(ans) - 1] == c {
            // if the current character is same as the last one in `ans`
            // then we cannot push it to `ans`
            // we remove the one in `ans`
            ans = ans[:len(ans) - 1]
        } else {
            // otherwise, add the current character to `ans`
            ans = append(ans, c)
        }
    }
    return string(ans)
}