Skip to content

Commit b32da14

Browse files
solves #3216: Lexicographically Smallest String After a Swap in java
1 parent 7e90579 commit b32da14

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -926,6 +926,6 @@
926926
| 3200 | [Maximum Height of a Triangle](https://leetcode.com/problems/maximum-height-of-a-triangle) | [![Java](assets/java.png)](src/MaximumHeightOfATriangle.java) | |
927927
| 3206 | [Alternating Groups I](https://leetcode.com/problems/alternating-groups-i) | [![Java](assets/java.png)](src/AlternatingGroupsI.java) | |
928928
| 3210 | [Find the Encrypted String](https://leetcode.com/problems/find-the-encrypted-string) | [![Java](assets/java.png)](src/FindTheEncryptedString.java) | |
929-
| 3216 | [Lexicographically Smallest String After a Swap](https://leetcode.com/problems/lexicographically-smallest-string-after-a-swap) | | |
929+
| 3216 | [Lexicographically Smallest String After a Swap](https://leetcode.com/problems/lexicographically-smallest-string-after-a-swap) | [![Java](assets/java.png)](src/LexicographicallySmallestStringAfterASwap.java) | |
930930
| 3222 | [Find the Winning Player in Coin Game](https://leetcode.com/problems/find-the-winning-player-in-coin-game) | | |
931931
| 3226 | [Number of Bit Changes to Make Two Integers Equal](https://leetcode.com/problems/number-of-bit-changes-to-make-two-integers-equal) | | |
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// https://leetcode.com/problems/lexicographically-smallest-string-after-a-swap
2+
// T: O(|s|)
3+
// S: O(|s|)
4+
5+
public class LexicographicallySmallestStringAfterASwap {
6+
public String getSmallestString(String s) {
7+
for (int i = 0 ; i < s.length() - 1 ; i++) {
8+
if (sameParity(s, i) && s.charAt(i) > s.charAt(i + 1)) {
9+
return swapCharWithNextChar(s, i);
10+
}
11+
}
12+
return s;
13+
}
14+
15+
private static boolean sameParity(String s, int index) {
16+
return Integer.parseInt(s.charAt(index) + "") % 2 ==
17+
Integer.parseInt(s.charAt(index + 1) + "") % 2;
18+
}
19+
20+
private static String swapCharWithNextChar(String s, int index) {
21+
return s.substring(0, index) + s.charAt(index + 1)
22+
+ s.charAt(index) + s.substring(index + 2);
23+
}
24+
}

0 commit comments

Comments
 (0)