字符串反转系列
- 344. Reverse String
- 345. Reverse Vowels of a String
- 541. Reverse String II
- 151. Reverse Words in a String
- 557. Reverse Words in a String III
- 917. Reverse Only Letters
- 2810. Faulty Keyboard
344. Reverse String
Write a function that reverses a string. The input string is given as an array of characters s
.
You must do this by modifying the input array in-place with O(1)
extra memory.
Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Constraints:
1 <= s.length <= 105
s[i]
is a printable ascii character.
思路
方法一:调包,使用String相关函数方法
方法二:双指针
The problem requires reversing a string in-place, which means directly modifying the input array without using additional memory for another array. A two-pointer approach works efficiently:
- Place one pointer at the beginning of the array and another at the end.
- Swap the characters at these two pointers.
- Move the pointers closer until they meet.
Complexity:
- Time Complexity: ( O(n) ), where ( n ) is the length of the array. Each element is processed once.
- Space Complexity: ( O(1) ), as no additional memory is used.
C++解法
class Solution {
public:
void reverseString(vector<char>& s) {
int left = 0;
int right = s.size() - 1;
while(left < right){
swap(s[left++], s[right--]);
}
}
};
Java解法
class Solution {
public void reverseString(char[] s) {
int left = 0, right = s.length - 1;
while (left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}
在Java中,字符串本身是不可变的,因此没有内置的 reverse
函数来直接反转字符串。不过,您可以使用 StringBuilder
或 StringBuffer
来实现字符串的反转,因为它们提供了一个 reverse()
方法。以下是两种实现方法的示例代码:
使用 StringBuilder
public class Main {
public static void main(String[] args) {
String original = "Hello, World!";
String reversed = new StringBuilder(original).reverse().toString();
System.out.println(reversed); // 输出: !dlroW ,olleH
}
}
使用 StringBuffer
public class Main {
public static void main(String[] args) {
String original = "Hello, World!";
String reversed = new StringBuffer(original).reverse().toString();
System.out.println(reversed); // 输出: !dlroW ,olleH
}
}
这些代码段通过 StringBuilder
或 StringBuffer
的 reverse()
方法反转给定的字符串,并将结果打印出来。
345. Reverse Vowels of a String
Given a string s
, reverse only all the vowels in the string and return it.
The vowels are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
, and they can appear in both lower and upper cases, more than once.
Example 1:
Input: s = "IceCreAm"
Output: "AceCreIm"
Explanation:
The vowels in s
are ['I', 'e', 'e', 'A']
. On reversing the vowels, s becomes "AceCreIm"
.
Example 2:
Input: s = "leetcode"
Output: "leotcede"
Constraints:
1 <= s.length <= 3 * 10^5
s
consist of printable ASCII characters.
思路
双指针,左右指针,找到元音字母就交换
C++解法
#include <string>
#include <unordered_set>
class Solution {
public:
std::string reverseVowels(std::string s) {
int left = 0;
int right = s.length() - 1;
// 定义元音字符集合
std::unordered_set<char> vowels{'a', 'e', 'i', 'o', 'u',
'A', 'E', 'I', 'O', 'U'};
while (left < right) {
// 找到左边的元音
while (left < right && vowels.find(s[left]) == vowels.end()) {
left++;
}
// 找到右边的元音
while (left < right && vowels.find(s[right]) == vowels.end()) {
right--;
}
// 如果左边的指针小于右边的指针,则交换元音字符
if (left < right) {
std::swap(s[left], s[right]);
left++;
right--;
}
}
return s; // 返回反转元音后的字符串
}
};
代码说明
-
头文件: 包含
<string>
和<unordered_set>
库,以便使用字符串和集合。 -
字符集合: 使用
std::unordered_set<char>
来存储元音字符,这使得查找是否是元音字符的复杂度为 O(1),提高了效率。 -
使用
std::swap
: C++ 已经提供了std::swap
函数来交换变量,因此直接使用这个函数来交换左右指针指向的字符。 -
循环结构: 循环结构与 Java 代码保持相同,确保左右指针逐步向中间靠拢,直到找到元音字符并进行交换。
Java解法
class Solution {
public String reverseVowels(String s) {
int left = 0;
int right = s.length() - 1;
char[] chars = s.toCharArray(); // 将字符串转换为字符数组,以便交换字符
// 定义元音字符集合
String vowels = "aeiouAEIOU";
while (left < right) {
// 找到左边的元音
while (left < right && !vowels.contains(String.valueOf(chars[left]))) {
left++;
}
// 找到右边的元音
while (left < right && !vowels.contains(String.valueOf(chars[right]))) {
right--;
}
// 如果左边的指针小于右边的指针,则交换元音字符
if (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
}
return new String(chars); // 将字符数组转换回来为字符串
}
}
修正的内容:
-
字符访问方式: 原代码使用
s.charAt[left]
,正确的方法是使用小括号s.charAt(left)
。 -
条件逻辑:
- 原来的条件使用了逻辑“或” (||),这会导致不正确的结果。应改为使用逻辑“与” (&&),要确保当前字符不是元音时才继续移动指针。
- 使用
!vowels.contains(...)
更简洁地判断一个字符是否是元音。
-
字符交换:
- 原先代码尝试调用
swap
函数,而在 Java 中没有直接对字符进行交换的函数,合理的做法是使用一个临时变量temp
来进行手动交换。
- 原先代码尝试调用
-
字符串与字符数组转换:
- Java 的字符串是不可变的,因此需要将字符串先转换为字符数组,进行所需的修改后再转换回字符串。
-
边界检查: 添加了
left < right
的检查,确保在交换之前左右指针仍然是有效的。
541. Reverse String II
Given a string s
and an integer k
, reverse the first k
characters for every 2k
characters counting from the start of the string.
If there are fewer than k
characters left, reverse all of them. If there are less than 2k
but greater than or equal to k
characters, then reverse the first k
characters and leave the other as original.
Example 1:
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Example 2:
Input: s = "abcd", k = 2
Output: "bacd"
Constraints:
1 <= s.length <= 10^4
s
consists of only lowercase English letters.1 <= k <= 10^4
思路
以2k为单位跳转,但只反转前k个字符
C++解法
class Solution {
public:
string reverseStr(string s, int k) {
for(int i = 0; i < s.size(); i += 2 * k){
if(i + k <= s.size()){
reverse(s.begin() + i,s.begin() + i + k);
continue;
}
reverse(s.begin() + i, s.end());
}
return s;
}
};
Java解法
151. Reverse Words in a String
Given an input string s
, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s
will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s
may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Example 1:
Input: s = "the sky is blue"
Output: "blue is sky the"
Example 2:
Input: s = " hello world "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: s = "a good example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
Constraints:
1 <= s.length <= 10^4
s
contains English letters (upper-case and lower-case), digits, and spaces' '
.- There is at least one word in
s
.
Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1)
extra space?
思路
先移除多余的空格然后再调整单词的位置
C++解法
class Solution {
public:
void reverse(string& s, int start, int end){ //翻转,区间写法:左闭右闭 []
for (int i = start, j = end; i < j; i++, j--) {
swap(s[i], s[j]);
}
}
void removeExtraSpaces(string& s) {//去除所有空格并在相邻单词之间添加空格, 快慢指针。
int slow = 0; //整体思想参考https://programmercarl.com/0027.移除元素.html
for (int i = 0; i < s.size(); ++i) { //
if (s[i] != ' ') { //遇到非空格就处理,即删除所有空格。
if (slow != 0) s[slow++] = ' '; //手动控制空格,给单词之间添加空格。slow != 0说明不是第一个单词,需要在单词前添加空格。
while (i < s.size() && s[i] != ' ') { //补上该单词,遇到空格说明单词结束。
s[slow++] = s[i++];
}
}
}
s.resize(slow); //slow的大小即为去除多余空格后的大小。
}
string reverseWords(string s) {
removeExtraSpaces(s); //去除多余空格,保证单词之间之只有一个空格,且字符串首尾没空格。
reverse(s, 0, s.size() - 1);
int start = 0; //removeExtraSpaces后保证第一个单词的开始下标一定是0。
for (int i = 0; i <= s.size(); ++i) {
if (i == s.size() || s[i] == ' ') { //到达空格或者串尾,说明一个单词结束。进行翻转。
reverse(s, start, i - 1); //翻转,注意是左闭右闭 []的翻转。
start = i + 1; //更新下一个单词的开始下标start
}
}
return s;
}
};
- 时间复杂度: O(n)
- 空间复杂度: O(1) 或 O(n),取决于语言中字符串是否可变
Java解法
class Solution {
/**
* 不使用Java内置方法实现
* <p>
* 1.去除首尾以及中间多余空格
* 2.反转整个字符串
* 3.反转各个单词
*/
public String reverseWords(String s) {
// System.out.println("ReverseWords.reverseWords2() called with: s = [" + s + "]");
// 1.去除首尾以及中间多余空格
StringBuilder sb = removeSpace(s);
// 2.反转整个字符串
reverseString(sb, 0, sb.length() - 1);
// 3.反转各个单词
reverseEachWord(sb);
return sb.toString();
}
private StringBuilder removeSpace(String s) {
// System.out.println("ReverseWords.removeSpace() called with: s = [" + s + "]");
int start = 0;
int end = s.length() - 1;
while (s.charAt(start) == ' ') start++;
while (s.charAt(end) == ' ') end--;
StringBuilder sb = new StringBuilder();
while (start <= end) {
char c = s.charAt(start);
if (c != ' ' || sb.charAt(sb.length() - 1) != ' ') {
sb.append(c);
}
start++;
}
// System.out.println("ReverseWords.removeSpace returned: sb = [" + sb + "]");
return sb;
}
/**
* 反转字符串指定区间[start, end]的字符
*/
public void reverseString(StringBuilder sb, int start, int end) {
// System.out.println("ReverseWords.reverseString() called with: sb = [" + sb + "], start = [" + start + "], end = [" + end + "]");
while (start < end) {
char temp = sb.charAt(start);
sb.setCharAt(start, sb.charAt(end));
sb.setCharAt(end, temp);
start++;
end--;
}
// System.out.println("ReverseWords.reverseString returned: sb = [" + sb + "]");
}
private void reverseEachWord(StringBuilder sb) {
int start = 0;
int end = 1;
int n = sb.length();
while (start < n) {
while (end < n && sb.charAt(end) != ' ') {
end++;
}
reverseString(sb, start, end - 1);
start = end + 1;
end = start + 1;
}
}
}
//解法二:创建新字符数组填充。时间复杂度O(n)
class Solution {
public String reverseWords(String s) {
//源字符数组
char[] initialArr = s.toCharArray();
//新字符数组
char[] newArr = new char[initialArr.length+1];//下面循环添加"单词 ",最终末尾的空格不会返回
int newArrPos = 0;
//i来进行整体对源字符数组从后往前遍历
int i = initialArr.length-1;
while(i>=0){
while(i>=0 && initialArr[i] == ' '){i--;} //跳过空格
//此时i位置是边界或!=空格,先记录当前索引,之后的while用来确定单词的首字母的位置
int right = i;
while(i>=0 && initialArr[i] != ' '){i--;}
//指定区间单词取出(由于i为首字母的前一位,所以这里+1,),取出的每组末尾都带有一个空格
for (int j = i+1; j <= right; j++) {
newArr[newArrPos++] = initialArr[j];
if(j == right){
newArr[newArrPos++] = ' ';//空格
}
}
}
//若是原始字符串没有单词,直接返回空字符串;若是有单词,返回0-末尾空格索引前范围的字符数组(转成String返回)
if(newArrPos == 0){
return "";
}else{
return new String(newArr,0,newArrPos-1);
}
}
}
//解法三:双反转+移位,String 的 toCharArray() 方法底层会 new 一个和原字符串相同大小的 char 数组,空间复杂度:O(n)
class Solution {
/**
* 思路:
* ①反转字符串 "the sky is blue " => " eulb si yks eht"
* ②遍历 " eulb si yks eht",每次先对某个单词进行反转再移位
* 这里以第一个单词进行为演示:" eulb si yks eht" ==反转=> " blue si yks eht" ==移位=> "blue si yks eht"
*/
public String reverseWords(String s) {
//步骤1:字符串整体反转(此时其中的单词也都反转了)
char[] initialArr = s.toCharArray();
reverse(initialArr, 0, s.length() - 1);
int k = 0;
for (int i = 0; i < initialArr.length; i++) {
if (initialArr[i] == ' ') {
continue;
}
int tempCur = i;
while (i < initialArr.length && initialArr[i] != ' ') {
i++;
}
for (int j = tempCur; j < i; j++) {
if (j == tempCur) { //步骤二:二次反转
reverse(initialArr, tempCur, i - 1);//对指定范围字符串进行反转,不反转从后往前遍历一个个填充有问题
}
//步骤三:移动操作
initialArr[k++] = initialArr[j];
if (j == i - 1) { //遍历结束
//避免越界情况,例如=> "asdasd df f",不加判断最后就会数组越界
if (k < initialArr.length) {
initialArr[k++] = ' ';
}
}
}
}
if (k == 0) {
return "";
} else {
//参数三:以防出现如"asdasd df f"=>"f df asdasd"正好凑满不需要省略空格情况
return new String(initialArr, 0, (k == initialArr.length) && (initialArr[k - 1] != ' ') ? k : k - 1);
}
}
public void reverse(char[] chars, int begin, int end) {
for (int i = begin, j = end; i < j; i++, j--) {
chars[i] ^= chars[j];
chars[j] ^= chars[i];
chars[i] ^= chars[j];
}
}
}
/*
* 解法四:时间复杂度 O(n)
* 参考卡哥 c++ 代码的三步骤:先移除多余空格,再将整个字符串反转,最后把单词逐个反转
* 有别于解法一 :没有用 StringBuilder 实现,而是对 String 的 char[] 数组操作来实现以上三个步骤
*/
class Solution {
//用 char[] 来实现 String 的 removeExtraSpaces,reverse 操作
public String reverseWords(String s) {
char[] chars = s.toCharArray();
//1.去除首尾以及中间多余空格
chars = removeExtraSpaces(chars);
//2.整个字符串反转
reverse(chars, 0, chars.length - 1);
//3.单词反转
reverseEachWord(chars);
return new String(chars);
}
//1.用 快慢指针 去除首尾以及中间多余空格,可参考数组元素移除的题解
public char[] removeExtraSpaces(char[] chars) {
int slow = 0;
for (int fast = 0; fast < chars.length; fast++) {
//先用 fast 移除所有空格
if (chars[fast] != ' ') {
//在用 slow 加空格。 除第一个单词外,单词末尾要加空格
if (slow != 0)
chars[slow++] = ' ';
//fast 遇到空格或遍历到字符串末尾,就证明遍历完一个单词了
while (fast < chars.length && chars[fast] != ' ')
chars[slow++] = chars[fast++];
}
}
//相当于 c++ 里的 resize()
char[] newChars = new char[slow];
System.arraycopy(chars, 0, newChars, 0, slow);
return newChars;
}
//双指针实现指定范围内字符串反转,可参考字符串反转题解
public void reverse(char[] chars, int left, int right) {
if (right >= chars.length) {
System.out.println("set a wrong right");
return;
}
while (left < right) {
chars[left] ^= chars[right];
chars[right] ^= chars[left];
chars[left] ^= chars[right];
left++;
right--;
}
}
//3.单词反转
public void reverseEachWord(char[] chars) {
int start = 0;
//end <= s.length() 这里的 = ,是为了让 end 永远指向单词末尾后一个位置,这样 reverse 的实参更好设置
for (int end = 0; end <= chars.length; end++) {
// end 每次到单词末尾后的空格或串尾,开始反转单词
if (end == chars.length || chars[end] == ' ') {
reverse(chars, start, end - 1);
start = end + 1;
}
}
}
}
Python解法
(版本一)先删除空白,然后整个反转,最后单词反转。 因为字符串是不可变类型,所以反转单词的时候,需要将其转换成列表,然后通过join函数再将其转换成列表,所以空间复杂度不是O(1)
class Solution:
def reverseWords(self, s: str) -> str:
# 反转整个字符串
s = s[::-1]
# 将字符串拆分为单词,并反转每个单词
# split()函数能够自动忽略多余的空白字符
s = ' '.join(word[::-1] for word in s.split())
return s
(版本二)使用双指针
class Solution:
def reverseWords(self, s: str) -> str:
# 将字符串拆分为单词,即转换成列表类型
words = s.split()
# 反转单词
left, right = 0, len(words) - 1
while left < right:
words[left], words[right] = words[right], words[left]
left += 1
right -= 1
# 将列表转换成字符串
return " ".join(words)
(版本三) 拆分字符串 + 反转列表
class Solution:
def reverseWords(self, s):
words = s.split() #type(words) --- list
words = words[::-1] # 反转单词
return ' '.join(words) #列表转换成字符串
(版本四) 将字符串转换为列表后,使用双指针去除空格
class Solution:
def single_reverse(self, s, start: int, end: int):
while start < end:
s[start], s[end] = s[end], s[start]
start += 1
end -= 1
def reverseWords(self, s: str) -> str:
result = ""
fast = 0
# 1. 首先将原字符串反转并且除掉空格, 并且加入到新的字符串当中
# 由于Python字符串的不可变性,因此只能转换为列表进行处理
s = list(s)
s.reverse()
while fast < len(s):
if s[fast] != " ":
if len(result) != 0:
result += " "
while s[fast] != " " and fast < len(s):
result += s[fast]
fast += 1
else:
fast += 1
# 2.其次将每个单词进行翻转操作
slow = 0
fast = 0
result = list(result)
while fast <= len(result):
if fast == len(result) or result[fast] == " ":
self.single_reverse(result, slow, fast - 1)
slow = fast + 1
fast += 1
else:
fast += 1
return "".join(result)
(版本五) 遇到空格就说明前面的是一个单词,把它加入到一个数组中。
class Solution:
def reverseWords(self, s: str) -> str:
words = []
word = ''
s += ' ' # 帮助处理最后一个字词
for char in s:
if char == ' ': # 遇到空格就说明前面的可能是一个单词
if word != '': # 确认是单词,把它加入到一个数组中
words.append(word)
word = '' # 清空当前单词
continue
word += char # 收集单词的字母
words.reverse()
return ' '.join(words)
Go解法
版本一:
func reverseWords(s string) string {
b := []byte(s)
// 移除前面、中间、后面存在的多余空格
slow := 0
for i := 0; i < len(b); i++ {
if b[i] != ' ' {
if slow != 0 {
b[slow] = ' '
slow++
}
for i < len(b) && b[i] != ' ' { // 复制逻辑
b[slow] = b[i]
slow++
i++
}
}
}
b = b[0:slow]
// 翻转整个字符串
reverse(b)
// 翻转每个单词
last := 0
for i := 0; i <= len(b); i++ {
if i == len(b) || b[i] == ' ' {
reverse(b[last:i])
last = i + 1
}
}
return string(b)
}
func reverse(b []byte) {
left := 0
right := len(b) - 1
for left < right {
b[left], b[right] = b[right], b[left]
left++
right--
}
}
版本二:
import (
"fmt"
)
func reverseWords(s string) string {
//1.使用双指针删除冗余的空格
slowIndex, fastIndex := 0, 0
b := []byte(s)
//删除头部冗余空格
for len(b) > 0 && fastIndex < len(b) && b[fastIndex] == ' ' {
fastIndex++
}
//删除单词间冗余空格
for ; fastIndex < len(b); fastIndex++ {
if fastIndex-1 > 0 && b[fastIndex-1] == b[fastIndex] && b[fastIndex] == ' ' {
continue
}
b[slowIndex] = b[fastIndex]
slowIndex++
}
//删除尾部冗余空格
if slowIndex-1 > 0 && b[slowIndex-1] == ' ' {
b = b[:slowIndex-1]
} else {
b = b[:slowIndex]
}
//2.反转整个字符串
reverse(b)
//3.反转单个单词 i单词开始位置,j单词结束位置
i := 0
for i < len(b) {
j := i
for ; j < len(b) && b[j] != ' '; j++ {
}
reverse(b[i:j])
i = j
i++
}
return string(b)
}
func reverse(b []byte) {
left := 0
right := len(b) - 1
for left < right {
b[left], b[right] = b[right], b[left]
left++
right--
}
}
557. Reverse Words in a String III
Given a string s
, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Example 2:
Input: s = "Mr Ding"
Output: "rM gniD"
Constraints:
1 <= s.length <= 5 * 10^4
s
contains printable ASCII characters.s
does not contain any leading or trailing spaces.- There is at least one word in
s
. - All the words in
s
are separated by a single space.
思路
通过设置start
变量确定反转范围
C++解法
class Solution {
public:
void reverse(string& s, int start, int end) {
for (int i = start, j = end; i < j; i++, j--) {
swap(s[i], s[j]);
}
}
string reverseWords(string s) {
int start = 0;
for (int i = 0; i <= s.size(); i++) {
if (i == s.size() || s[i] == ' ') {
reverse(s, start, i - 1);
start = i + 1;
}
}
return s;
}
};
917. Reverse Only Letters
Given a string s
, reverse the string according to the following rules:
- All the characters that are not English letters remain in the same position.
- All the English letters (lowercase or uppercase) should be reversed.
Return s
after reversing it.
Example 1:
Input: s = "ab-cd"
Output: "dc-ba"
Example 2:
Input: s = "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Example 3:
Input: s = "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"
Constraints:
1 <= s.length <= 100
s
consists of characters with ASCII values in the range[33, 122]
.s
does not contain'\"'
or'\\'
.
思路
This problem is exactly like reversing a normal string except that there are certain characters that we have to simply skip. That should be easy enough to do if you know how to reverse a string using the two-pointer approach.
C++解法
class Solution {
public:
string reverseOnlyLetters(string s) {
int left = 0;
int right = s.length() - 1;
while(left < right){
while(left < right && !isalpha(s[left])) left++;
while(left < right && !isalpha(s[right])) right--;
swap(s[left++], s[right--]);
}
return s;
}
};
2810. Faulty Keyboard
Your laptop keyboard is faulty, and whenever you type a character 'i'
on it, it reverses the string that you have written. Typing other characters works as expected.
You are given a 0-indexed string s
, and you type each character of s
using your faulty keyboard.
Return the final string that will be present on your laptop screen.
Example 1:
Input: s = "string"
Output: "rtsng"
Explanation: After typing first character, the text on the screen is "s". After the second character, the text is "st". After the third character, the text is "str". Since the fourth character is an 'i', the text gets reversed and becomes "rts". After the fifth character, the text is "rtsn". After the sixth character, the text is "rtsng". Therefore, we return "rtsng".
Example 2:
Input: s = "poiinter"
Output: "ponter"
Explanation: After the first character, the text on the screen is "p". After the second character, the text is "po". Since the third character you type is an 'i', the text gets reversed and becomes "op". Since the fourth character you type is an 'i', the text gets reversed and becomes "po". After the fifth character, the text is "pon". After the sixth character, the text is "pont". After the seventh character, the text is "ponte". After the eighth character, the text is "ponter". Therefore, we return "ponter".
Constraints:
1 <= s.length <= 100
s
consists of lowercase English letters.s[0] != 'i'
思路
Try to build a new string by traversing the given string and reversing whenever you get the character ‘i’.
注意:s[0] != 'i'
,reverse时注意不要发生数组越界问题
C++解法
class Solution {
public:
void reverse(string &s, int start, int end){
for(int i = start, j = end; i < j; i++, j--){
swap(s[i], s[j]);
}
}
string finalString(string s) {
string result = "";
for(int j = 0; j < s.length(); j++){
if(s[j] == 'i'){
reverse(result, 0, result.size() - 1);
}else{
result += s[j];
}
}
return result;
}
};