|
| 1 | +public class BuddyString { |
| 2 | + public static void main(String[] args) { |
| 3 | + System.out.println(new BuddyString().buddyStrings("aaaaaaabc","aaaaaaacb")); |
| 4 | + } |
| 5 | + public boolean buddyStrings(String a, String b) { |
| 6 | + StringBuffer str1 = new StringBuffer(a); |
| 7 | + StringBuffer str2 = new StringBuffer(b); |
| 8 | + boolean flag = false; |
| 9 | + |
| 10 | + int len = str1.length()>str2.length()? str1.length():str2.length(); |
| 11 | +// if(a.equals(b)) |
| 12 | +// return true; |
| 13 | + |
| 14 | + for(int i = 0; i<len-1; i++){ |
| 15 | + try { |
| 16 | + char tmp = ' '; |
| 17 | + tmp = str2.charAt(i); |
| 18 | + str2.replace(i,i+1,String.valueOf(str2.charAt(i+1))); |
| 19 | + str2.replace(i+1,i+2,String.valueOf(tmp)); |
| 20 | + |
| 21 | + if(str1.toString().equals(str2.toString())) |
| 22 | + return flag = true; |
| 23 | + else { |
| 24 | + tmp = str2.charAt(i); |
| 25 | + str2.replace(i,i+1,String.valueOf(str2.charAt(i+1))); |
| 26 | + str2.replace(i+1,i+2,String.valueOf(tmp)); |
| 27 | + } |
| 28 | + |
| 29 | + }catch (IndexOutOfBoundsException e){ |
| 30 | + return false; |
| 31 | + } |
| 32 | + } |
| 33 | + return flag; |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +/* O(N) 출처: LeetCode |
| 38 | +class Solution { |
| 39 | + public boolean buddyStrings(String A, String B) { |
| 40 | + if (A.length() != B.length()) return false; |
| 41 | + if (A.equals(B)) { |
| 42 | + int[] count = new int[26]; |
| 43 | + for (int i = 0; i < A.length(); ++i) |
| 44 | + count[A.charAt(i) - 'a']++; |
| 45 | +
|
| 46 | + for (int c: count) |
| 47 | + if (c > 1) return true; |
| 48 | + return false; |
| 49 | + } else { |
| 50 | + int first = -1, second = -1; |
| 51 | + for (int i = 0; i < A.length(); ++i) { |
| 52 | + if (A.charAt(i) != B.charAt(i)) { |
| 53 | + if (first == -1) |
| 54 | + first = i; |
| 55 | + else if (second == -1) |
| 56 | + second = i; |
| 57 | + else |
| 58 | + return false; |
| 59 | + } |
| 60 | + } |
| 61 | +
|
| 62 | + return (second != -1 && A.charAt(first) == B.charAt(second) && |
| 63 | + A.charAt(second) == B.charAt(first)); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | + */ |
0 commit comments