recursion moving char to the end of the string - java

i need to get a string and rearrange it with recursion by getting char and by that char i have to move that char everywhere on the string to the end
like "Hello world!" ,'l' => "Heo word!lll"
i have problems understading the recursion way of thinking
so i started with this:
public static String ChToLast (String str, char ch){
if(str.indexOf(ch)== -1){
return str;
}else{
if(str.indexOf(0) == ch){
return str;
}
}
thank you for your help :)

Recursion is the practise of reusing your method inside itself. In this case, I will provide a solution to explain what happens:
public static String chrToLast(String str, char ch) {
//This if statement details the end condition
if(str.length() < 1) {
return "";
}
String newString = str.substring(1); //Create new string without first character
if(str.indexOf(ch) == 0) { //This happens when your character is found
return chrToLast(newString, ch) + ch;
} else { //This happens with all other characters
return str.charAt(0) + chrToLast(newString, ch);
}
}
If you execute:
chrToLast("Hello, World!", 'l')
This will result in the desired result: Heo, Word!lll
Process
In general, this method works by checking which character is currently the first in the given string, and then deciding what to do. If the first character is the same as the one your looking for (l), it will then remove that character from the string and use chrToLast on that new string. But, it also adds the character it found to the end of the result by using + ch. It continues to do this until there are no more characters left, which is what the end condition is for.
The end condition
The end condition returns an empty string "" because that is what is called the base case of the algorithm. You can think of a recursive algorithm as something solving a problem by calling itself a number of times. By calling themselves, recursive algorithms move towards a base. In this particular case, it does that by subtracting one character off the string each time the method is executed. Once there are no characters left, it reaches the base case which is "", where the string is finally empty and no characters can be subtracted anymore. (Hence it returns nothing as it's final state)
I hope this answers your question. It's important to understand this concept, as it is very powerful. Try to study the code and comment if something's not clear.
Something that can also help is by executing this code in an IDE and using the debugger to walk through its execution. You can then see for yourself what the flow of the program is, and see the value of the variables in play.

If you use recursion, it will be pretty expensive call for the result you are expecting. Lot of movement of String or charArray elements, eitherway you do. I don't see its a wiser choice. I would do it this way, it will be of space complexity O(2n) & performance complexity O(n).
public class Solve {
public static void main(String[] args) {
System.out.println(ChToLast("Hello world!", 'l'));
}
public static String ChToLast(String str, char ch) {
char[] chars = str.toCharArray();
char[] modChars = new char[chars.length];
int i = 0;
for(char element : chars){
if(ch != element){
modChars[i++] = element;
}
}
Arrays.fill(modChars, i, chars.length , ch);
return new String(modChars);
}
}

If you use while loop and write a method to check if that string means perfect statement then that may work for you
Here you would need some help of NLP concept to check everytime if arranged chars are making any statement or are grammatically correct.
This will help

Related

I am trying to write a recursive function that checks if one word matches the reverse word but im not sure if its recursion

All I really need to know is if the function I am using is recursive or if the method simply doesnt get called within itself.
In my code, I have a helper function to reverse the second word and I put a toLowerCase in order to be able to compare words even if there are any random capitals.
Is this recursion or is it just a function that compares the two?
import java.util.Scanner;
public class isReverse {
public static void main(String[] args) {
isReverse rev = new isReverse();
Scanner in = new Scanner(System.in);
System.out.println("Please enter a word: ");
String a = in.nextLine();
System.out.println("Please Enter a second word to compare: ");
String b = in.nextLine();
System.out.println(rev.isReverse(a, b));
}
String rev = "";
public boolean isReverse(String wordA, String wordB){
String fword = wordA.replaceAll("\\s+", "").toLowerCase();
String clean2 = wordB.replaceAll("\\s+", "").toLowerCase();
String reverse = revString(clean2);
if(fword.length() == 0){
return false;
}
if (fword.equals(reverse)){
return true;
}
if (!reverse.equals(fword)){
return false;
}
else
return isReverse(fword,reverse);
}
public String revString(String sequence) {
String input = sequence;
StringBuilder order = new StringBuilder();
order.append(input);
order = order.reverse();
rev = order.toString();
return rev;
}
}
As far as your question is concerned, your code is not behaving like a recursive function because your code is not entering into the last else condition. For recursion to work you need to have:
a base case(if there is no base case the recursion will go on forever)
a recursive case(this is where you kind of reduce the original problem)
But my comment about your code:
If you're doing the actual reverse logic you don't need to use recursion just to check if the original string and the reverse string are the same. These is purely an algorithm problem so here is the way to solve the problem:
If the length of the given input is 1 then the reverse is the same.
else:
check the first and last chars of the string, if they are equal, then you need to remove those two chars and check if the rest of the string is a palindrome. This is the actual recursive step.
else the string is not a palindrome.
Technically? Well, you are calling a method from within itself, so, technically, yeah.
Pragmatically? No. The recursive call part will never be invoked.
Your code does this: I have 2 words. If the words are equal to each other, stop and do something. if they are not equal to each other, stop and do something. Otherwise, recurse.
And that's where it falls apart: It'll never recurse - either the words are equal, or they are not.
The general idea behind a recursive function is three-fold:
The method (java-ese for 'function') calls itself.
Upon each call to itself, the parameters passed are progressing to an end state - they become smaller or trend towards a stop value such as 0.
There are edge cases where the function does not call itself, and returns instead (the answer for the smallest/zero-est inputs does not require recursion and is trivial).
You're missing the #2 part here. Presumably, this is what you'd want for a recursive approach. Forget about revString, delete that entirely. Do this instead:
If both inputs are completely empty, return true (That's the #3 - edge cases part).
If one of the two inputs is empty but the other one is not, false. (Still working on #3)
If the first character of the input string is NOT equal to the last character of the output string, false. (Still #3).
Now lop the first char off of the first input and the last off of the latter (Working on #2 now - by shortening the strings we're inevitably progressing towards an end no matter what)
now call ourself, with these new lopped-down strings (That'll be #1).
That would be a recursive approach to the problem. It's more complicated than for loops, but, then, recursive functions often are.
Actually this is not a recursing. All you need is just:
Check that both string have the same length
Iteratively check letters from 0 to n from the first string and from n to 0 from the second string. If they equal, then go to the next iteration (recutsion) or return fail otherqwise.
// here do not check signature of the public method
public static boolean isReverse(String one, String two) {
return isReverse(one, 0, two, two.length() - 1);
}
// support method has two additional counters to check letters to be equal
private static boolean isReverse(String one, int i, String two, int j) {
if (i == one.length())
return j == -1;
if (j == two.length())
return i == -1;
// if not equal, then strings are not equal
if (one.charAt(i) != two.charAt(j))
return false;
// go to the next recursion to check next letters
return isReverse(one, i + 1, two, j - 1);
}

Removing special character without using Java Matcher and Pattern API

I am trying to write one java program. This program take a string from the user as an input and display the output by removing the special characters in it. And display the each strings in new line
Let's say I have this string Abc#xyz,2016!horrible_just?kidding after reading this string my program should display the output by removing the special characters like
Abc
xyz
2016
horrible
just
kidding
Now I know there are already API available like Matcher and Patterns API in java to do this. But I don't want to use the API since I am a beginner to java so I am just trying to crack the code bit by bit.
This is what I have tried so far. What I have done here is I am taking the string from the user and stored the special characters in an array and doing the comparison till it get the special character. And also storing the new character in StringBuilder class.
Here is my code
import java.util.*;
class StringTokens{
public void display(String string){
StringBuilder stringToken = new StringBuilder();
stringToken.setLength(0);
char[] str = {' ','!',',','?','.','_','#'};
for(int i=0;i<string.length();i++){
for(int j =0;j<str.length;j++){
if((int)string.charAt(i)!=(int)str[j]){
stringToken.append(str[j]);
}
else {
System.out.println(stringToken.toString());
stringToken.setLength(0);
}
}
}
}
public static void main(String[] args){
if(args.length!=1)
System.out.println("Enter only one line string");
else{
StringTokens st = new StringTokens();
st.display(args[0]);
}
}
}
When I run this code I am only getting the special characters, I am not getting the each strings in new line.
One easy way - use a set to hold all invalid characters:
Set<Character> invalidChars = new HashSet<>(Arrays.asList('$', ...));
Then your check boils down to:
if(invaidChars.contains(string.charAt(i)) {
... invalid char
} else {
valid char
}
But of course, that still means: you are re-inventing the wheel. And one does only re-invent the wheel, if one has very good reasons to. One valid reason would be: your assignment is to implement your own solution.
But otherwise: just read about replaceAll. That method does exactly what your current code; and my solution would be doing. But in a straight forward way; that every good java programmer will be able to understand!
So, to match your question: yes, you can implement this yourself. But the next step is to figure the "canonical" solution to the problem. When you learn Java, then you also have to focus on learning how to do things "like everybody else", with least amount of code to solve the problem. That is one of the core beauties of Java: for 99% of all problems, there is already a straight-forward, high-performance, everybody-will-understand solution out there; most often directly in the Java standard libraries themselves! And knowing Java means to know and understand those solutions.
Every C coder can put down 150 lines of low-level array iterating code in Java, too. The true virtue is to know the ways of doing the same thing with 5 or 10 lines!
I can't comment because I don't have the reputation required. Currently you are appending str[j] which represents special character. Instead you should be appending string.charAt(i). Hope that helps.
stringToken.append(str[j]);
should be
stringToken.append(string.charAt(i));
Here is corrected version of your code, but there are better solutions for this problem.
public class StringTokens {
static String specialChars = new String(new char[]{' ', '!', ',', '?', '.', '_', '#'});
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Enter only one line string");
} else {
display(args[0]);
}
}
public static void display(String string) {
StringBuilder stringToken = new StringBuilder();
stringToken.setLength(0);
for(char c : string.toCharArray()) {
if(!specialChars.contains(String.valueOf(c))) {
stringToken.append(c);
} else {
stringToken.append('\n');
}
}
System.out.println(stringToken);
}
}
public static void main(String[] args) {
String a=",!?#_."; //Add other special characters too
String test="Abc#xyz,2016!horrible_just?kidding"; //Make this as user input
for(char c : test.toCharArray()){
if(a.contains(c+""))
{
System.out.println(); //to avoid printing the special character and to print newline
}
else{
System.out.print(c);
}
}
}
you can run a simple loop and check ascii value of each character. If its something other than A-Z and a-z print newline skip the character and move on. Time complexity will be O(n) + no extra classes used.
String str = "Abc#xyz,2016!horrible_just?kidding";
char charArray[] = str.toCharArray();
boolean flag=true;;
for (int i = 0; i < charArray.length; i++) {
int temp2 = (int) charArray[i];
if (temp2 >= (int) 'A' && temp2 <= (int) 'Z') {
System.out.print(charArray[i]);
flag=true;
} else if (temp2 >= (int) 'a' && temp2 <= (int) 'z') {
System.out.print(charArray[i]);
flag=true;
} else {
if(flag){
System.out.println("");
flag=false;
}
}
}

How can I compute the previous and next chars?

My goal is to return a string that is made up of characters that are 1 before and 1 after each character in the given string in the ASCII table.
For example, dog should return cenpfh.
public String encrypt(String s) {
if (s.length() == 1) {
String one = "";
one += (s.charAt(0)-1) + (s.charAt(0)+1);
return one;
} else { .. }
}
This is the code I have so far, and I have no idea how to continue. This doesn't even work for a single character, for example, "172" is returned for "V". Could anyone point me in the right direction? Really stumped right now.
If you have to use recursion, you can try something like that:
public static String encrypt(final String s) {
if (s.length() == 1) {
final char c = s.charAt(0);
return new String(new char[] {(char) (c - 1), (char) (c + 1)});
} else {
return encrypt(s.substring(0, 1)) + encrypt(s.substring(1));
}
}
the main idea here:
if input length is 1 symbol - we know what to do and just perform "encryption"
if input length is more than 1 symbol - we split string into "first symbol" and "rest of the string" and call itself on both parts
This is fairly tricky stuff for a beginner, but it's good stuff to encounter early and understand.
"" + 172
results in the string "172"
"" + 'V'
results in the string "V".
V and 172 are both represented internally as the same number, so what's the difference? The difference is that the compiler keeps track of the type of the value. 'V' has a type of char. 172 has a type of int.
When you perform an expression using a mixture of types, the compiler has to decide what the type of the result is. This will influence how that result is handled by routines such String concatenation.
As it happens when you subtract an int from a char, the type of the result is an int (the Java spec tells you this).
You can get around it by casting the type to something else.
(char) 172 is 'V'
(int) 'V' is 172.
So:
one += (char) (s.charAt(0)-1) + (char)(s.charAt(0)+1);
Recursion is a separate topic. Recursion works for handling sequences (a String is a sequence of characters) when you can do a chunk of work on a part of the sequence, leaving you with a new, shorter sequence, that you can do the same job on -- until finally you have the simplest case, which you simply return.
The simplest case, the one where the method returns without recursively calling itself, is called the terminating case. You need at least one terminating case, otherwise the recursive method will keep calling itself until Java runs out of memory for storing method states.
You have chosen your terminating case as being a one char string. I would instead pick a zero length string:
public void encrypt(String s) {
if("".equals(s)) {
return "";
} else {
// do something with a string that's guaranteed >1 char
}
Now you just have to work out how to replace that comment, by using up the guaranteed one char, and calling encrypt() to handle what's left.
public void encrypt(String s) {
if("".equals(s)) {
return "";
} else {
return encodeOneChar(s.charAt(0)) +
encrypt(x.substring(1));
}
}
That's it:
when called with an empty string, encode() returns an empty string.
when called with a non-empty string, encode processes the first char
and calls itself to deal with a string that's one shorter.
Some languages, like Haskell, make recursion easier to understand, by representing the cases as pattern matching statements.
encrypted "" == ""
encrypted s == encryptChar(head(s)) + encrypted(tail(s))
(that's not real Haskell, but it illustrates the pattern.)
Recursion isn't quite as easy to read in Java, but the pattern is still there. if(terminating case) { return answer for terminating case } else { calculate something, call self, return combined result }
I'll leave you to implement private String encodeOneChar(char c)
Note that recursion isn't a good solution to your actual task in Java -- except in the sense that your goal is to understand recursion.
There is no recursion needed. Just iterate over input chars and collect result in a StringBuilder:
public static String encrypt(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
sb.append((char)(c - 1)).append((char)(c + 1));
}
return sb.toString();
}
Note that explicit cast to char is required here, because s.charAt(i) - 1 evaluates to int and without cast is processed by overloaded append(int i) method.
Okay, recursion. Here I split input into 2 halves and process each by using the same encryptRecursively() method, then join results. Each part, when passed to the method, is again split into 2 parts, etc, until size becomes 0 or 1 (thus we get a very simple implementation of Divide and Conquer):
public static String encryptRecursively(String s) {
if (s.isEmpty())
return "";
else if (s.length() == 1) {
char c = s.charAt(0);
return new String(new char[] { (char)(c - 1), (char)(c + 1) });
} else {
int mid = s.length() / 2;
return encryptRecursively(s.substring(0, mid)) // process first half of input
+ encryptRecursively(s.substring(mid)); // second half
}
}
You don't need a recursion but a simple for-loop through all chars in the word. You get the value of char with s.charAt(...), but you have to convert it back to char for the desired resut. Append them to StringBuilder and return its String as the output of the method:
public static String encrypt(String s) {
StringBuilder sb = new StringBuilder();
for (int i=0; i<s.length(); i++) {
char a = (char)(s.charAt(i)-1);
char b = (char)(s.charAt(i)+1);
sb.append(a).append(b);
}
return sb.toString();
}
Here is the recursion method as demanded:
public static String encrypt(String s) {
if (s.length() == 1) {
StringBuilder sb = new StringBuilder();
char a = (char)(s.charAt(0)-1);
char b = (char)(s.charAt(0)+1);
return sb.append(a).append(b).toString();
} else {
return encrypt(s.substring(0, 1)) + encrypt(s.substring(1, s.length()));
}
You can try this:
one += (char)(((int)s.charAt(0))-1);
one += (char)(((int)s.charAt(0))+1);
Input:
V
Output:
UW

New to programming - ***Updated*** PracticeProblem throwing StringIndexOutOfBoundsException

I'm trying to teach myself Java and I've recently been doing online practice problems with a built in compiler. My code is working great for most of the conditions except for two in which the string length is less than two.
The URL to this specific practice problem is: http://codingbat.com/prob/p123384
Problem:
Given a string, return a new string where the first and last chars have been exchanged.
Example
frontBack("code") should be→ "eodc"
frontBack("a") should be→ "a"
frontBack("ab") should be→ "ba"
Here's my code:
public String frontBack(String str) {
char firstChar = str.charAt (0);
char lastChar = str.charAt (str.length()-1);
String middle = str.substring(1, str.length()-1);
if (str.length()>=3){
return lastChar + middle + firstChar;
}
else {
return new StringBuilder(str).reverse().toString();
}
}
These are the two conditions that error
frontBack("a") should be→ "a"
"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:4)"
frontBack("") should be→ ""
"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 0 (line number:2)"
Here's the solution, the code that works
public String frontBack(String str) {
if (str.length() <= 1) return str;
String mid = str.substring(1, str.length()-1);
// last + mid + first
return str.charAt(str.length()-1) + mid + str.charAt(0);
}
What's the difference between my code and the solution?
Any help would be great. I'm confused on this one since my else statement simply returns the original string. Why would any of the variables (frontChar, middle, lastChar) affect the original string I'm returning? Thanks in advance!
First I want to say thank you to everyone that helped me!*
I've reworked my code and narrowed it down to one simple difference. That difference is the placement of an explicit statement to account for strings equal to or less than one. This apparently can't be handled implicitly by a catch-all else statement. Still not exactly sure why? Here is the same code with one minor difference; Explicit vs Implicit
This code works... Explicitly return str if string length is less than or equal to 1.
public String frontBack(String str) {
// This line below is the only difference
if (str.length() <= 1) {
return str;
}
char firstChar = str.charAt (0);
char lastChar = str.charAt (str.length()-1);
String middle = str.substring(1, str.length()-1);
if (str.length()>=2){
return lastChar + middle + firstChar;
}
else {
return str;
}
}
This code doesn't work... Implicitly return str with an else statement if string length is less than or equal to 1.
public String frontBack(String str) {
char firstChar = str.charAt (0);
char lastChar = str.charAt (str.length()-1);
String middle = str.substring(1, str.length()-1);
if (str.length()>=2){
return lastChar + middle + firstChar;
}
else {
return str;
}
}
You need to program to defend
1.
for one character String
String middle = str.substring(1, str.length()-1);
this would be
str.substring(1, 0)
which is invalid
2.
for empty string (length = 0 ) your code will attempt to look at index = -1 which is invalid, or even index = 0 is invalid
3.
what if str is null
You always have to think of boundary conditions:
str is null? str is empty("") str is 1 char?
also bear in mind that Java's substring is inclusive on start position but exclusive on the end.
public String frontBack(String str) {
if (str == null || str.length()<2){
//if str is null - return empty. else return the string itself
return str == null ? "" : str;
}else{
//do the actual first last swap
return str.charAt(str.length()-1)+ str.substring(1,str.length()-1) + str.charAt(0);
}
}
I've reworked my code and narrowed it down to one simple difference. That difference is the placement of an explicit statement to account for strings equal to or less than one. This apparently can't be handled implicitly by a catch-all else statement. Still not exactly sure why?
It has nothing to do with implicit or explicit. The problem is simply the sequence in which the lines are executed within the method, which is top to bottom.
By the time it gets to your if/else in the "implicit" case, the three lines above, such as char firstChar = str.charAt(0); have already happened (or already failed). For an empty string it will blow up with a StringIndexOutOfBounds exception immediately on that line (look at the line number of the exception), and the method will stop executing then as it throws the exception out of the method. (The technical term for this is abrupt completion.) If that exception is thrown, the below if/else won't happen, so it cannot retroactively prevent the exception afterwards. That code will work fine if you move the three string-using statements from the top of the method to inside the 'if' branch of the if/else, so that they are not executed when not wanted.
In the "explicit" case, you added if (str.length() <= 1) return str; at the top of the method, where it can prevent the lines below from executing, because the return statement will exit the method before the attempts to use the non-existent characters of the string. That statement wouldn't help if it was lower down in the method.
I just want to add something about 'null', since other answerers on this page have complained that your code doesn't defend against a null argument. It's good to think about how your method will cope with peculiar input, but here, your code already does correctly defend against a null argument, because when you try to call charAt or length or substring on null, it will throw a NullPointerException out of the method, as it should.
Sometimes null should be checked for and allowed, but here it should not. If called without a valid string, what might frontBack be expected to return? Some might say it should return null, some might say it should return the empty string, and some might say it should coerce it to a string and thus return "luln". There is no fully sensible or unambiguously correct way to handle it that will work for all callers. So, frontBack should take the stance that null is not an acceptable input. Then it is the caller's fault if they pass in null, and if the caller passes in garbage, it's correct that they should get the garbage thrown back at them (metaphorically, of course; you will actually throw an exception object, not the original input) so they are forced to deal with it properly. Tolerating and making excuses for bad callers by explicitly coercing garbage to valid input is the wrong thing to do because it hides errors and it makes the program's behavior more subtle.
If the method had side effects, such as modifying a data structure, writing to a file, or calling other methods with side effects, then null input could be dangerous, because the method might complete some of the side effects without using str. Then, trying to use str would at some point throw the exception, leaving things half-finished and in an invalid state. Ideally, the side effects should be observed to happen either entirely or not at all. In that case, it would be good to check for null and throw the exception yourself at the top of the method:
if (str == null) throw new NullPointerException();
That won't make a difference in this simple method because it has no side effects (it is purely functional) and because it already unconditionally calls methods on str, which will cause the same exception to be thrown anyway.

Recursive removal of characters in Java

As an exercise, the code block below intends to recursively go through a string and remove all the of the "x" characters. It does that, but I would like to keep track of the newStr without passing it as a parameter in the method. Is there anyway to move it into the method body?
Thanks!
public static String deathToX(String str, String newStr) {
//look for x char
if(str.substring(0, 1).equals("x")) {
//do nothing
} else {
//add non-x char to newStr
newStr += str.charAt(0);
}
if(str.length() == 1) {
return newStr;
}
return deathToX(str.substring(1), newStr);
}
public static void main(String[] args) {
System.out.println("Return: " + deathToX("xnoxmore", ""));
}
Well, you could change the code to:
public static String deathToX(String str)
{
// Termination case
if (str.length() == 0)
{
return str;
}
// Work out whether or not we want the first character
String prefix = str.startsWith("x") ? "" : str.substring(0, 1);
// Let the recursive call handle the rest of the string, and return
// the prefix (empty string or the first character) followed by the
// x-stripped remainder.
return prefix + deathToX(str.substring(1));
}
Is that the sort of thing you were thinking of?
Of course, this is a horribly inefficient way of doing string manipulation, but I assume you're more interested in the recursive nature of things.
I would like to keep track of the newStr without passing it as a parameter in the method.
Why? Passing the intermediary result into the function is often required in functional-style recursive programming. What I do is make a function that handles the bulk of the work and accepts the accumulator, and make a wrapper function that calls the previous one with the required starter value:
private static String deathToX0(String str, String newStr) {
// the original implementation
}
public static String deathToX(String str) {
return deathToX(str, "");
}
As an aside, you might not want to use a String for the intermediate result because of the copying involved. A StringBuilder would be faster.
The short answer is yes... with recursion typically on the way down the tree you work out the bit at each level in this case blank or the current character. So the return statement should call itself recursively then at the bottom of the tree the answer you wanted is reconstructed by adding together the sections at each level.
public static String deathToX(String str){
if (!str.isEmpty()){
return (str.substring(0, 1).equals("x") ? "" : str.substring(0, 1)) + deathToX(str.substring(1));
}else{
return "";
}
}
public static void main(String[] args){
System.out.println("Return: " + deathToX("xnoxmore"));
}
In the sample above I used the shorthand if format to put it all on one line but you could expand it out. You should be able to see that the recursive function recurses on the return statement and I put in a special case for the last level. If you were to split it and put this levels answer in a local variable e.g. tmp then you would use:
return tmp + deathToX(str.substring(1));
Remember recursion means that the current execution is only paused until the lower ones finish so you can happily store info to recover on your way back up. Hope this helps :)
public class solution {
// Return the changed string
public static String removeX(String input){
if(input.equals("") || input.equals("x"))
return "";
String returnStr="";
removeX(input.substring(1));
for(int i=0;i<input.length();i++)
{
if(input.charAt(i)=='x')
continue;
else
returnStr+=input.charAt(i);
}
return returnStr;
}
}
This is my approach. This code goes to the end of the string, if it gets X as last string, it returns ""(nothing), then it checks the whole substring for "x", if its present in the string, it will continue, else it will append rest character to that string and it goes on.
Finally returns the updated string.!
Hope this helps..!! well, this is my first contribution here :)

Categories

Resources