Given a string
S
, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.Example 1:
Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba
Approach
Java
public class ReverseOnlyLetters {public static void main(String[] args) {String str = "a-bC-dEf-ghIj";System.out.println(reverseOnlyLetters(str));}static String reverseOnlyLetters(String str) {Stack<Character> st = new Stack<Character>();char[] s = str.toCharArray();for (int i = 0; i < s.length; i++) {if (s[i] >= 'A' && s[i] <= 'Z')st.push(s[i]);else if (s[i] >= 'a' && s[i] <= 'z')st.push(s[i]);}for (int i = 0; i < s.length; i++) {if (s[i] >= 'a' && s[i] <= 'z') {s[i] = st.pop();} else if (s[i] >= 'A' && s[i] <= 'Z') {s[i] = st.pop();}}return new String(s);}}
C++
#include <bits/stdc++.h>using namespace std;string reverseOnlyLetters(string s){stack<char> st;for (int i = 0; i < s.size(); i++){if (s[i] >= 'A' && s[i] <= 'Z')st.push(s[i]);else if (s[i] >= 'a' && s[i] <= 'z')st.push(s[i]);}for (int i = 0; i < s.size(); i++){if (s[i] >= 'a' && s[i] <= 'z'){s[i] = st.top();st.pop();}else if (s[i] >= 'A' && s[i] <= 'Z'){s[i] = st.top();st.pop();}}return s;}int main(){string str = "a-bC-dEf-ghIj";cout << reverseOnlyLetters(str);return 0;}
No comments:
Post a Comment