Skip to content

Commit 2c10ca4

Browse files
authored
Create 2000. Reverse Prefix of Word (#470)
2 parents 63263ef + e9eb89d commit 2c10ca4

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

2000. Reverse Prefix of Word

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public:
3+
string reversePrefix(string word, char ch) {
4+
string ans;
5+
6+
// Find the index of the character 'ch' in the word
7+
int ind = 0;
8+
for(int i = 0; i < word.length(); i++){
9+
if(word[i] == ch){
10+
ind = i;
11+
break;
12+
}
13+
}
14+
15+
// Push characters onto a stack until the index 'ind'
16+
stack<char> st;
17+
for(int i = 0; i <= ind; i++) st.push(word[i]);
18+
19+
// Pop characters from the stack to reverse the prefix
20+
while(!st.empty()){
21+
ans += st.top();
22+
st.pop();
23+
}
24+
25+
// Append the remaining characters after 'ch'
26+
for(int i = ind+1; i < word.length(); i++) ans += word[i];
27+
28+
return ans;
29+
}
30+
};

0 commit comments

Comments
 (0)