File tree Expand file tree Collapse file tree 2 files changed +31
-1
lines changed Expand file tree Collapse file tree 2 files changed +31
-1
lines changed Original file line number Diff line number Diff line change 230
230
| 844 | [ Backspace String Compare] ( https://leetcode.com/problems/backspace-string-compare ) | [ ![ Java] ( assets/java.png )] ( src/BackspaceStringCompare.java ) |
231
231
| 849 | [ Maximize Distance to Closest Person] ( https://leetcode.com/problems/maximize-distance-to-closest-person ) | |
232
232
| 852 | [ Peak Index in Mountain Array] ( https://leetcode.com/problems/peak-index-in-a-mountain-array ) | [ ![ Java] ( assets/java.png )] ( src/PeakIndexInMountainArray.java ) |
233
- | 859 | [ Buddy Strings] ( https://leetcode.com/problems/buddy-strings ) | |
233
+ | 859 | [ Buddy Strings] ( https://leetcode.com/problems/buddy-strings ) | [ ![ Java ] ( assets/java.png )] ( src/BuddyStrings.java ) |
234
234
| 860 | [ Lemonade Change] ( https://leetcode.com/problems/lemonade-change ) | |
235
235
| 867 | [ Transpose Matrix] ( https://leetcode.com/problems/transpose-matrix ) | |
236
236
| 868 | [ Binary Gap] ( https://leetcode.com/problems/binary-gap ) | |
Original file line number Diff line number Diff line change
1
+ import java .util .Arrays ;
2
+
3
+ public class BuddyStrings {
4
+ public boolean buddyStrings (String s , String goal ) {
5
+ if (s .length () != goal .length ()) return false ;
6
+ final int [] characterFrequencies = new int [26 ];
7
+ final int [] need = new int [26 ];
8
+ int differences = 0 ;
9
+ char c ;
10
+ for (int index = 0 ; index < s .length () ; index ++) {
11
+ c = s .charAt (index );
12
+ characterFrequencies [c - 'a' ]++;
13
+ if (c != goal .charAt (index )) {
14
+ differences ++;
15
+ need [goal .charAt (index ) - 'a' ]++;
16
+ need [c - 'a' ]--;
17
+ }
18
+ }
19
+ if (differences == 1 || differences > 2 ) return false ;
20
+ if (differences == 0 && oneCharOccurrsMoreThanOnce (characterFrequencies )) return true ;
21
+ return differences == 2 && Arrays .stream (need ).allMatch (val -> val == 0 );
22
+ }
23
+
24
+ private boolean oneCharOccurrsMoreThanOnce (int [] frequencies ) {
25
+ for (int frequency : frequencies ) {
26
+ if (frequency > 1 ) return true ;
27
+ }
28
+ return false ;
29
+ }
30
+ }
You can’t perform that action at this time.
0 commit comments