Reverse an array items without affecting any special characters position
💻 coding

Reverse an array items without affecting any special characters position

1 min read 154 words
1 min read
ShareWhatsAppPost on X
  • 1The algorithm reverses alphabetic characters in a string while keeping special characters in their original positions.
  • 2For the input 'x%y?z', the output is 'z%y?x', demonstrating the reversal of only the letters.
  • 3The provided Java code implements this functionality using a two-pointer technique to swap characters.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The algorithm reverses alphabetic characters in a string while keeping special characters in their original positions."

Reverse an array items without affecting any special characters position

In a given string, which also contains special character along with alphabets (‘a’ to ‘z’ and ‘A’ to ‘Z’), reverse the string items in such a way that special character positions are not changed

Input: str = "x%y?z"
Output: str = "z%y?x"
Note that ? and % are not moved anywhere. 
Only subsequence "xyz" is reversed
public class ReverseArrayWithoutSpecialChars {
	
	public static void reverse(char[] str) {
		int start=0;
		int end= str.length-1;
		for(;start<end;) {
			if((str[start] >= 65 && str[start] <=90) || (str[start] >= 97 && str[start] <=122)) {
				if((str[end] >= 65 && str[end] <=90) || (str[end] >= 97 && str[end] <=122)) {
					char temp = str[start];
					str[start]=str[end];
					str[end]=temp;
					start++;
					end--;
				}
				else {
					end--;
				}
			}
			else {
				start++;
			}
		}
	}
	
 public static void main(String[] args) 
 {
 String str = "x%y?z";
 char[] charArray = str.toCharArray();
 
 System.out.println("Input string: " + str);
 reverse(charArray);
 String revStr = new String(charArray);
 
 System.out.println("Output string: " + revStr);
 }
}

.

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 12 July 2018 · 1 min read · 154 words

Part of AskGif Blog · coding

You might also like