LeetCode-859 Buddy Strings Solution (with Java)

1. Description:

Notes:

2. Examples:

3.Solutions:

 1 /**
 2  * Created by sheepcore on 2018-12-24
 3  */
 4 class Solution {
 5     public boolean buddyStrings(String s1, String s2) {
 6         if (s1.equals(s2))
 7             return isLetterShowTwice(s1) ? true : false;
 8         else if (s1.length() != s2.length())
 9             return false;
10         char[] str = new char[4];
11         int flag = 0;
12         for (int i = 0; i < s1.length(); i++)
13             if (s1.charAt(i) != s2.charAt(i))
14                 if (flag < 4) {
15                     str[flag] = s1.charAt(i);
16                     //System.out.println(s1.charAt(i));
17                     str[flag + 1] = s2.charAt(i);
18                     //System.out.println(s2.charAt(i));
19                     flag += 2;
20                 } else
21                     return false;
22         return (str[0] == str[3] && str[1] == str[2]) ? true : false;
23     }
24 
25     public  boolean isLetterShowTwice(String s) {
26             byte[] alphate = new byte[26];
27         for (char ch : s.toCharArray()) {
28             alphate[ch - 'a']++;
29             if (alphate[ch - 'a'] > 1)
30                 return true;
31         }
32         return false;
33     }
34 }

猜你喜欢

转载自www.cnblogs.com/sheepcore/p/12396485.html
今日推荐