2023年9月17日 星期日

9/17 每日一題(檢查s是否可以透過調換順序變成goal)

 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].

  • For example, swapping at indices 0 and 2 in "abcd" results in "cbad".

 

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:

  • 1 <= s.length, goal.length <= 2 * 104
  • s and goal consist of lowercase letters.

class Solution:
    def buddyStrings(self, s: str, goal: str) -> bool:

        if s==goal:
            '檢查有沒有交換空間'
            '如果字母數量=長度,那就沒有'
            if len(set(s))==len(s):
                return False
            else:
                return True
        else:
            s=list(s)
            goal=list(goal)
            n=0
            err_index=[]
            for i,j in zip(s,goal):
               
                if i != j:
                    err_index.append(n)
                n+=1
            if err_index:
       
                s[err_index[0]],s[err_index[-1]]=s[err_index[-1]],s[err_index[0]]

            return s == goal



       


       

       


標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁