145、僅僅反轉字母
阿新 • • 發佈:2019-01-01
題目描述:
給定一個字串 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 "
class Solution { public String reverseOnlyLetters(String S) { char [] tem = S.toCharArray(); int start = 0; int end = tem.length -1; while (start < end) { //找到對應的字母 while(tem[start] < 65 || (tem[start] > 90 && tem[start] <97) || tem[start] > 122){ start ++; if(start == tem.length || start >= end ){ return new String(tem); } } //找到對應的字母 while(tem[end] < 65 || (tem[end]>90 && tem[end] <97) || tem[end] > 122){ if(end == 0 || start >= end){ return new String(tem); }else { end --; } } char s = tem[start]; tem [start] = tem[end]; tem[end] = s; start ++; end --; } // System.out.println(tem); return new String(tem); } }