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
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 :-
- Create the character array from the input String.
- 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.
- Move the first variable to right, if the character at first is not a letter (a-z || A-Z).
- Move the second variable to left, if the character at second is not a letter (a-z || A-Z).
- 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.
- 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
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.