(Easy) Reverse Only Letters - LeetCode

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:

  1. S.length <= 100
  2. 33 <= S[i].ASCIIcode <= 122 
  3. S doesn't contain \ or "
Accepted 32,931 Submissions 58,770

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;
    }
}

 

上一篇:如何在JavaScript中检测字母字符?


下一篇:C# 泛型隐式转换