1. 程式人生 > >Java/971. 僅僅反轉字母

Java/971. 僅僅反轉字母

題目

程式碼部分一(15ms)

class Solution {
    public String reverseOnlyLetters(String S) {
        int n = 0;
        String res = "";
        Map<Integer, String> map = new HashMap<>();
        int len = S.length();
        for(int i = 0; i < len; i++){
            char temp = S.charAt(i);
            if(temp < 'A' || temp > 'z' || temp < 'a' && temp > 'Z')
                map.put(i, temp + "");
        }
        for(int i = len - 1; i >= 0; i--){
            char temp = S.charAt(i);
            while(map.containsKey(n)) 
                n++;
            if(temp >= 'A' && temp <= 'Z' || temp >= 'a' && temp <='z'){
                
                map.put(n++, temp+ "");
            }
        }
        for(int j = 0; j < len; j++){
            res += map.get(j);
        }
        
        return res;
    }
}