917. Reverse Only Letters

917. Reverse Only Letters

class Solution {
    public String reverseOnlyLetters(String s) {
        char[] arr = s.toCharArray();
            int arrIndex = getNextEmpty(arr.length,arr);

        for(int i = 0 ; i < s.length(); i++){
                char c = s.charAt(i);
                if((c>='a' && c <='z') ||
                    (c>='A' && c <='Z')){
                    arr[arrIndex] = c;
                    arrIndex = getNextEmpty(arrIndex,arr);
                    }
        }
        return new String(arr);
    }
    public int getNextEmpty(int current, char[] arr){
        for(int i = current-1; i >=0; i--){
            char c = arr[i];
            if((c >='a' && c <='z') ||
                    (c>='A' && c <='Z')) return i;
        }
        return 0;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s