Reverse only Letters of a String | String Problem | LeetCode 917

4 years ago Lalit Bhagtani 0

Problem Statement

You have given a String, write a program to reverse all the letters (a-z and A-Z) of the input string. Characters that are not a letter stays at their place in the string.

Example 

Reverse only Letters of a String

Input :- "ab-cd"
Output :- "dc-ba"
Input :- "sun-rise-in-the-morning"
Output :- "gni-nrom-eh-tni-esirnus"

Solution

This problem can be solved in following steps :-

  1. Create the character array from the input String.
  2. Create three variables first pointing to index 0, second pointing to last index (n-1, where n is the length of an array) and temp.
  3. Move the first variable to right, if the character at first is not a letter (a-z || A-Z).
  4. Move the second variable to left, if the character at second is not a letter (a-z || A-Z).
  5. If character at both first and second variables are letters then copy the character at first variable to temp, the character at second variable to first and character at temp variable to second.
  6. Repeat steps 3, 4 and 5, until first is less than second.

Program

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		String result = main.reverseOnlyLetters("sun-rise-in-the-morning");
		System.out.print(result);
	}
	
	/* Solution */
	public String reverseOnlyLetters(String str) {
        char[] array = str.toCharArray();
        
        int first = 0, second = array.length-1;
        char temp;
        boolean isStartFound = false, isEndFound = false;
        while(first < second){
            
            if((array[first]>='a' && array[first]<='z') || (array[first]>='A' && array[first]<='Z')){
                isStartFound = true;
            }else {
            	first++;
            }
            
            if((array[second]>='a' && array[second]<='z') || (array[second]>='A' && array[second]<='Z')){
                isEndFound = true;
            }else {
            	second--;
            }
            
            if(isStartFound && isEndFound){
                temp = array[second];
                array[second] = array[first];
                array[first] = temp;
                isStartFound = false;
                isEndFound = false;
                first++;
                second--;
            }
        }        
        return String.valueOf(array);        
    }
}

Result

gni-nrom-eh-tni-esirnus

Similar Post

  1. Shifting Letters of a String
  2. Custom Order Sorting of String
  3. Detect Capital in String

That’s all for Reverse only Letters of a String in Java, If you liked it, please share your thoughts in a comments section and share it with others too.