LeetCode in Kotlin

859. Buddy Strings

Easy

Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.

Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].

Example 1:

Input: s = “ab”, goal = “ba”

Output: true

Explanation: You can swap s[0] = ‘a’ and s[1] = ‘b’ to get “ba”, which is equal to goal.

Example 2:

Input: s = “ab”, goal = “ab”

Output: false

Explanation: The only letters you can swap are s[0] = ‘a’ and s[1] = ‘b’, which results in “ba” != goal.

Example 3:

Input: s = “aa”, goal = “aa”

Output: true

Explanation: You can swap s[0] = ‘a’ and s[1] = ‘a’ to get “aa”, which is equal to goal.

Constraints:

Solution

class Solution {
    fun buddyStrings(s: String, goal: String): Boolean {
        var first = -1
        val second: Int
        val sCounts = IntArray(26)
        if (s == goal) {
            for (i in s.indices) {
                sCounts[s[i].code - 'a'.code]++
                if (sCounts[s[i].code - 'a'.code] > 1) {
                    return true
                }
            }
        }
        for (i in s.indices) {
            val curr = s[i]
            sCounts[curr.code - 'a'.code]++
            if (curr != goal[i]) {
                if (first == -1) {
                    first = i
                } else {
                    second = i
                    val ss = s.toCharArray()
                    val temp = ss[first]
                    ss[first] = ss[second]
                    ss[second] = temp
                    return String(ss) == goal
                }
            }
        }
        return false
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy