JAVA - Reverse String without temp String,array,Stringbuilder,substring [英] JAVA - Reverse String without temp String, array, Stringbuilder, substring

查看:173
本文介绍了JAVA - Reverse String without temp String,array,Stringbuilder,substring的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题。
所以,我必须用这个要求反转一个String:


  1. 只能使用:1个变量字符串可变char& 1个变量int

  2. 不能使用其他字符串,字符串构建器,列表,数组或集合


  3. 不能增加输入变量的长度

  4. 不能使用函数substring

然后我试试这个,是否正确?

  String str =Hello World 

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

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

System.out.println(str);

}

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

输出:





ello WorldH



llo WorldeH



WorldleH



o WorldlleH



WorldolleH



世界olleH



orldW olleH



rldoW olleH



ldroW olleH



dlroW olleH



dlroW olleH



之后:dlroW olleH

解决方案

您可以对任务使用递归,类似如下:

  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);
}


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

解决方案

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);
}

这篇关于JAVA - Reverse String without temp String,array,Stringbuilder,substring的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆