JAVA - Reverse String without temp String, array,

2019-08-11 12:43发布

问题:

I have a question for you. So, I have to reverse a String with this requirement :

  1. Only use : 1 variable string (for input), 1 variable char & 1 variable int
  2. Can't use another string, string builder, list, array or collections
  3. Output result assigned in input variable
  4. Length of input variable can't be increase
  5. Can't use function substring

And then I try this, is this correct?

  String str = "Hello World";  

  System.out.println("Before : "+str);

  for(int i=0;i<str.length();i++){

   str = new String(str.getBytes(), 1, str.length()-1-i) + new String(str.getBytes(), 0, 1) + new String(str.getBytes(), str.length()-i, i);

   System.out.println(str);

  }

  System.out.println("After : "+str);

Output :

Before : Hello World

ello WorldH

llo WorldeH

lo WorldleH

o WorldlleH

WorldolleH

World olleH

orldW olleH

rldoW olleH

ldroW olleH

dlroW olleH

dlroW olleH

After : dlroW olleH

回答1:

You can use recursion to the task, something like this:

public static String reverse(String source, int from) {
    if (source.length()-from == 1) {
        return source.charAt(from)+"";
    }
    return reverse(source, from+1) + source.charAt(from);
}


回答2:

String is an immutable class in java any methods which seem to modify it always return a new string object with modification. So the answer is, NO you cannot reverse a String in-place in Java. Java String's are implemented as wrappers around a char array, which is hidden from you (i.e. you can only get copies of this array via normal means).



回答3:

Only use : 1 variable string (for input), 1 variable char & 1 variable int

This implies, that the desired solution is:

  • Take character from position n from String, store to character variable.
  • Move variable m to n (in string).
  • restore cached char from character variable to position m.
  • repeat until string is fully processed.

This is a typical question asked for "basic" programming languages. However Java does not allow for this, as it leaks the option to set a character based on position within a string.

While this is a no brainer in other languages, java has no option to set values based on an index for Strings.

public static String reverse(String str){
        char c;
        int i = 0;

        for (i=0; i< str.length() / 2; i++){
            c = str.charAt(i);

            //this would be required to match your requirements.
            str[i] = str.charAt(str.length() -1 -i);    
            str[str.length() -1 -i] = c;            
        }

        return str;
    }

but in java, you can only do:

public static String reverse(String str){
    char c;
    int i = 0;

    for (i=0; i< str.length() / 2; i++){
        c = str.charAt(i);
        char[] temp = str.toCharArray();
        temp[i] = str.charAt(str.length() -1-i);
        temp[str.length() -1 -i] = c;
        str = new String(temp);
    }

    return str;
}

which creates additional char arrays and new String objects... Even if you could lower this to one additional char array by declaring it out of the for- loop, it does no longer match the requirement.

I think the guy designing the question was thinking in "C" or "php", where index-based access on strings is possible.

If a String would equal a char-array (which it does in some older languages, that might be the origin of this exercise) it would look like this:

public static char[] reverse(char[] str){
    char c;
    int i = 0;

    for (i=0; i< str.length / 2; i++){
        c = str[i];
        str[i] = str[str.length -1-i];
        str[str.length -1 -i] = c;
    }

    return str;
}


回答4:

Without using any collection,StringBulider, StringBuffer or temp array reverse the string. Simple and crisp:

public static void main(String[] args) {

    String test = "Hello World";
    String rev = "";
    Pattern p = Pattern.compile("[\\w|\\W]");
    Matcher m = p.matcher(test);
    while (m.find()) {
        rev = m.group()+rev;
    }
    System.out.println("Reverse==" + rev);
}

Output

Reverse==dlroW olleH

Hope it helps :)