Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitab79856

Browse files
committed
Updated Buddy Strings.java
1 parent52111fe commitab79856

File tree

1 file changed

+17
-18
lines changed

1 file changed

+17
-18
lines changed

‎Easy/Buddy Strings.java

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,32 @@
11
classSolution {
2+
3+
privatestaticfinalintSWAP_DONE_IDX =Integer.MIN_VALUE;
4+
25
publicbooleanbuddyStrings(Strings,Stringgoal) {
36
if (s.length() !=goal.length()) {
47
returnfalse;
58
}
6-
intmismatchIdx = -1;
9+
intswapIdx = -1;
710
Set<Character>set =newHashSet<>();
811
for (inti =0;i <s.length();i++) {
12+
if (s.charAt(i) ==goal.charAt(i)) {
13+
set.add(s.charAt(i));
14+
continue;
15+
}
916
if (s.charAt(i) !=goal.charAt(i)) {
10-
if (mismatchIdx ==Integer.MAX_VALUE) {
17+
if (swapIdx ==SWAP_DONE_IDX) {
1118
returnfalse;
1219
}
13-
if (mismatchIdx == -1) {
14-
mismatchIdx =i;
15-
}else {
16-
if (!(s.charAt(mismatchIdx) ==goal.charAt(i) &&s.charAt(i) ==goal.charAt(mismatchIdx))) {
17-
returnfalse;
18-
}
19-
mismatchIdx =Integer.MAX_VALUE;
20+
if (swapIdx == -1) {
21+
swapIdx =i;
22+
continue;
23+
}
24+
if (!(s.charAt(swapIdx) ==goal.charAt(i) &&s.charAt(i) ==goal.charAt(swapIdx))) {
25+
returnfalse;
2026
}
21-
}else {
22-
set.add(s.charAt(i));
27+
swapIdx =SWAP_DONE_IDX;
2328
}
2429
}
25-
if (mismatchIdx != -1 &&mismatchIdx !=Integer.MAX_VALUE) {
26-
returnfalse;
27-
}
28-
if (mismatchIdx == -1) {
29-
returns.length() >set.size();
30-
}
31-
returntrue;
30+
return (swapIdx != -1 &&swapIdx ==SWAP_DONE_IDX) || (swapIdx == -1 &&set.size() <s.length());
3231
}
3332
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp