给定一个字符串 S
,返回 “反转后的” 字符串,其中不是字母的字符都保留在原地,而所有字母的位置发生反转。
示例 1:
输入:"ab-cd" 输出:"dc-ba"
示例 2:
输入:"a-bC-dEf-ghIj" 输出:"j-Ih-gfE-dCba"
示例 3:
输入:"Test1ng-Leet=code-Q!" 输出:"Qedo1ct-eeLg=ntse-T!"
提示:
S.length <= 100
33 <= S[i].ASCIIcode <= 122
S
中不包含or
"
思路:这是一道简单难度的题目, 从头尾同时遍历
两者同时是字母,则交换,否则不是字母的一方索引递增或递减 ,见代码 目前 beat 100%
class Solution { //65-90 97-122 public String reverseOnlyLetters(String S) { char[] ch = S.toCharArray(); for(int i=0,j=ch.length-1;i<j;){ if(isAlp(ch[i])==1 && isAlp(ch[j])==1) { swap(ch,i,j); ++i;--j; } else { if(isAlp(ch[i])==0) ++i; else if(isAlp(ch[j])==0) --j; else {++i;--j;} } } return new String(ch); } //是否是字母 是为1,不是为0 public int isAlp(char i){ if((i>=65 && i<=90)||(i>=97 && i<=122)) return 1; return 0; } //交换 char temp=0; public void swap(char[] ch,int i,int j){ temp = ch[j]; ch[j]= ch[i]; ch[i]= temp; } }