145、仅仅反转字母

题目描述:
给定一个字符串 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);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34446716/article/details/85496560