• LeetCode 859. Buddy Strings


    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.

    题目要求两个string,能否通过只交换两个字符来变成另一个string。想来其实很简单,计算一下有几个字符不同,然后看看他们的下标是否能交换就行了。但是实际写起来踩了不少坑:

    1. 在"aa"和"aa"这种情况,diffCount = 0,所以需要判断两个string是否相同,如果是相同的string那就要看这个string里有没有重复出现两或以上的字符 

    2. 最开始写的时候,在循环里面就判断了if diffCount == 2直接看是否能swap就return,其实又可能到这儿都是符合的但是后面就不对应了,所以只能最后return了

    3. char[diffCount]写成了char[i]……

    1. class Solution {
    2. public boolean buddyStrings(String s, String goal) {
    3. int diffCount = 0;
    4. char[] diffS = new char[2];
    5. char[] diffGoal = new char[2];
    6. Set<Character> set = new HashSet<>();
    7. boolean repeat = false;
    8. if (s.length() != goal.length()) {
    9. return false;
    10. }
    11. for (int i = 0; i < s.length(); i++) {
    12. if (set.contains(s.charAt(i))) {
    13. repeat = true;
    14. }
    15. set.add(s.charAt(i));
    16. if (s.charAt(i) != goal.charAt(i)) {
    17. if (diffCount < 2) {
    18. diffS[diffCount] = s.charAt(i);
    19. diffGoal[diffCount] = goal.charAt(i);
    20. }
    21. diffCount++;
    22. }
    23. }
    24. if (diffCount == 0) {
    25. return repeat;
    26. } else if (diffCount == 2) {
    27. return diffS[0] == diffGoal[1] && diffS[1] == diffGoal[0];
    28. }
    29. return false;
    30. }
    31. }

  • 相关阅读:
    操作系统学习-进程的描述与控制
    【Java项目推荐之黑马头条】自媒体文章实现异步上下架(使用Kafka中间件实现)
    Redis设计与实现(2)链表和链表节点
    识别户口本易语言代码
    香港服务器怎么解除被封ip?
    C#/VB.NET 创建PDF/UA文件
    Cython
    Java微服务+分布式+全栈项目(一)---->项目介绍+MyBatis-Plus入门
    【牛客网】HJ92 在字符串中找出连续最长的数字串(C++)
    面试官:Java反射是什么?我回答不上来
  • 原文地址:https://blog.csdn.net/qq_37333947/article/details/127889657