-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReversePrefix.java
39 lines (36 loc) · 1.03 KB
/
ReversePrefix.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Approach 1 : Insert at start and concatenate
class Solution {
public String reversePrefix(String word, char ch) {
StringBuilder res = new StringBuilder();
for(int i = 0; i < word.length(); i++){
char cur = word.charAt(i);
res.insert(0, cur);
if(cur == ch){
res.append(word.substring(i + 1, word.length()));
return res.toString();
}
}
return word;
}
}
// Approach 2 : Swap the characters
class Solution {
public String reversePrefix(String word, char ch) {
char res[] = word.toCharArray();
int L = 0;
for(int R = 0; R < word.length(); R++){
char cur = res[R];
if(cur == ch){
while(L < R){
char t = res[R];
res[R] = res[L];
res[L] = t;
L++;
R--;
}
return new String(res);
}
}
return word;
}
}