Description:
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: "ab-cd" Output: "dc-ba"
Example 2:
Input: "a-bC-dEf-ghIj" Output: "j-Ih-gfE-dCba"
Example 3:
Input: "Test1ng-Leet=code-Q!" Output: "Qedo1ct-eeLg=ntse-T!"
Note:
S.length <= 100
-
33 <= S[i].ASCIIcode <= 122
-
S
doesn't contain\
or"
Solution:
class Solution { public String reverseOnlyLetters(String S) { if(S==null|| S.length()==0){ return S; } String res = ""; int k = S.length()-1; for(int i =0; i< S.length();i++){ if(checkAlpha(S.charAt(i))){ char tmp='-'; for(int t = k;t>=0; k--){ if(checkAlpha(S.charAt(k))){ tmp = S.charAt(k); k=k-1; break; } } res = res+tmp; } else{ res = res+S.charAt(i); } } return res; } public boolean checkAlpha(char A){ if(((int)A>=65&&(int)A<=90) ||((int)A>=97&&(int)A<=122) ) return true; else return false; } }