859.Buddy Strings

Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B

给定两个字符串,如果只交换其中两个字符的位置就能使两个字符串相同,则返回true.

思路:

1. 首先两个字符串的长度必定大于2而且长度需要相同

2.思考什么情况下能够交换两个字符串就能使字符串A和B相同

(1)字符串有两个位置不相同,其余位置均相同;

(2)字符串所有位置均相同,并且至少有一个重复的字符。

public static boolean buddyStrings(String A, String B) {
        if((A.length()<2 || B.length()<2) || A.length()!=B.length()) return false;
        int l= Integer.MAX_VALUE,r = Integer.MAX_VALUE;  //用于记录不同字符串的位置
        int count = 0 , o=0;
        for (int i = 0; i < A.length(); i++) {
            if(A.charAt(i)==B.charAt(i)){
                count++; 
            }else {
                if(o==0){
                    o++;
                    l = i;
                }else {
                    r = i;
                }
            }
        }
        if(count==A.length()-2){
            char c1 = A.charAt(l);
            char c2 = A.charAt(r);
            StringBuffer sb = new StringBuffer(A);
            sb.setCharAt(l, c2);
            sb.setCharAt(r, c1);
            System.out.println(sb.toString());
            if(sb.toString().equals(B)){
                return true;
            }else{
                return false;
            }
        }else if(count == A.length()){
            int c[] = new int[26];
            for (int i = 0; i < A.length(); i++) {
                c[A.charAt(i)-97]++;
                if((c[A.charAt(i)-97])>=2){  //判断是否有重复的字符
                    return true;
                }
            }
            return false;
        }else{
            return false;
        }
    }

猜你喜欢

转载自blog.csdn.net/make_a_great_effort/article/details/82776943
今日推荐