917. 僅僅反轉字母
阿新 • • 發佈:2018-11-09
給定一個字串 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
中不包含\
"
思路:這是一道簡單難度的題目, 從頭尾同時遍歷
兩者同時是字母,則交換,否則不是字母的一方索引遞增或遞減 ,見程式碼 目前 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)) return1; return 0; } //交換 char temp=0; public void swap(char[] ch,int i,int j){ temp = ch[j]; ch[j]= ch[i]; ch[i]= temp; } }