859. Buddy Strings

1. Question

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

2. Examples

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.

Example 4:

Input: s = "aaaaaaabc", goal = "aaaaaaacb"
Output: true

3. Constraints

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

4. References

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/buddy-strings 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

5. Solutions

比较细节的模拟题。

class Solution {
  public boolean buddyStrings(String s, String goal) {
    if (s.length() != goal.length()) {
      return false;
    }

    int[] arr1 = new int[26];
    int[] arr2 = new int[26];
    int diff = 0;
    boolean flag = false;

    for(int i = 0; i < s.length(); i++) {
      int a = s.charAt(i) - 'a';
      int b = goal.charAt(i) - 'a';

      arr1[a]++;
      arr2[b]++;

      // 标记同一位置上字符不同的数量
      if(a != b) {
        diff++;
      }
    }

    for(int i = 0; i < arr1.length; i++) {
      // 如果所含字符数量本身不同,那么不可能构成亲密字符串
      if (arr1[i] != arr2[i]) {
        return false;
      }
      // 如果所有字符的数量相等,但有两个及以上相同的字符串,则也可构成亲密字符串
      if (arr1[i] >= 2) {
        flag = true;
      }
    }

    return diff == 2 || (diff == 0 && flag);
  }
}
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2022-05-18 16:24:00

results matching ""

    No results matching ""