Reverse String, Unchanged position of special characters.
Reverse a string keeping the position of special characters unchanged in reversed string.
ex.
i/p - a,b#d$e&d
o/p - d,e#d$b&a
Solution :-
static boolean isAlphabet(char x) {
return (x >= 'A' && x <= 'Z' ) || (x >= 'a' && x <= 'z' );
}
public static void main(String[] args) {
String s = "Ab,c,de!$";//a,b$c";
System.out.println("Original String:- " + s);
char[] str = s.toCharArray();
int l = 0;
int r = s.length() - 1;
while (l<r) {
if(!isAlphabet(str[l])) {
l++;
}else if(!isAlphabet(str[r])) {
r--;
}else{
char a = str[l];
char b = str[r];
str[l] = b;
str[r] = a;
l++;
r--;
}
}
System.out.println("Reversed String:- " + new String(str));
}
}
ex.
i/p - a,b#d$e&d
o/p - d,e#d$b&a
Solution :-
static boolean isAlphabet(char x) {
return (x >= 'A' && x <= 'Z' ) || (x >= 'a' && x <= 'z' );
}
public static void main(String[] args) {
String s = "Ab,c,de!$";//a,b$c";
System.out.println("Original String:- " + s);
char[] str = s.toCharArray();
int l = 0;
int r = s.length() - 1;
while (l<r) {
if(!isAlphabet(str[l])) {
l++;
}else if(!isAlphabet(str[r])) {
r--;
}else{
char a = str[l];
char b = str[r];
str[l] = b;
str[r] = a;
l++;
r--;
}
}
System.out.println("Reversed String:- " + new String(str));
}
}
Comments