反转字符串,不使用反转函数或循环。

huangapple go评论72阅读模式
英文:

Reversing a String Without Reverse Function or loops

问题

public class reverseMe {
  public String reverseMe(String s) {
         if(s.length() == 0)
            return "";
            return s.charAt(s.length() - 1) + reverseMe(s.substring(0,s.length()-1));
 }
}
英文:

So I have to reverse a string but like an example would be reverse Hello World. Well my code reverses it like this dlroW olleH and you have to reverse it like World Hello. This is my code below can someone help me fix it or tell me what im doing wrong please. I need to do as you create a new object and input the data through the object and then call the method.

public class reverseMe {
  public String reverseMe(String s) {
         if(s.length() == 0)
            return "";
            return s.charAt(s.length() - 1) + reverseMe(s.substring(0,s.length()-1));
 }
}



答案1

得分: 2

什么意思是“没有反转功能或循环”。首先,在 Java 中称为方法而不是函数,其次以某种方式需要迭代字符串。这段代码只是使用递归方法来完成任务。从构造函数中调用它,就完成了。没有任何内置的 Java 方法来实现你想要的功能。

public class HelloWorld{

public String recursiveReverse(String[] words,StringBuilder b,int length){
     if (length < 0) 
        return b.toString();
     else{
        b.append(words[length] + " ");
        length--;
        return recursiveReverse(words,b,length);
     }
            
}

public String reverse (String input){
   String[] words = input.split(" ");
   StringBuilder reverse = new StringBuilder();
   return recursiveReverse(words,reverse,words.length-1);
}

     public static void main(String []args){
        HelloWorld a = new HelloWorld();
        System.out.println(a.reverse("hello this is a test reverse this string"));
     }
}

输出:

string this reverse test a is this hello
英文:

What do you mean for "without reverse function or loops". First of all in java are called methods, not functions, and second in some way you need to iterate the strings. This code just does the job with a recursive method. Call it from your constructor and you’re done. There aren't any already built-in java methods to do what you want.

public class HelloWorld{


public String recursiveReverse(String[] words,StringBuilder b,int length){
     if (length &lt; 0) 
        return b.toString();
     else{
        b.append(words[length] + &quot; &quot;);
        length--;
        return recursiveReverse(words,b,length);
     }
            
}

public String reverse (String input){
   String[] words = input.split(&quot; &quot;);
   StringBuilder reverse = new StringBuilder();
   return recursiveReverse(words,reverse,words.length-1);
}

     public static void main(String []args){
        HelloWorld a = new HelloWorld();
        System.out.println(a.reverse(&quot;hello this is a test reverse this string&quot;));
     }
}

Output:

string this reverse test a is this hello

答案2

得分: 1

这个答案假设以下内容:

  • 不能使用内置的 reverse() 函数,例如在 StringBuilderCollections 中找到的。

  • 不能使用循环。

  • 输入可以包含任意数量的单词。

  • 单词之间用一个空格分隔。

首先,最简单的解决方案是使用 split() 函数来分割输入,然后使用流(Stream)逻辑以相反的顺序组合单词,但是我认为流逻辑也被视为“循环逻辑”,所以这不行。

这留下了使用递归方法作为解决方案,类似于问题中的尝试:

static String reverseWords(String input) {
    int idx = input.indexOf(' ');
    if (idx == -1)
        return input;
    return reverseWords(input.substring(idx + 1)) + ' ' + input.substring(0, idx);
}

测试

System.out.println(reverseWords("Hello World"));
System.out.println(reverseWords("The quick brown fox jumps over the lazy dog"));

输出

World Hello
dog lazy the over jumps fox brown quick The
英文:

This answer assumes the following:

  • Can't use built-in reverse() function, such as found on StringBuilder and Collections.

  • Can't use loops.

  • Input can contain any number of words.

  • Words are separated by a single space.

First, the easiest solution would be to split() the input and then use Stream logic to combine the words in reverse order, however I consider Stream logic to be "Loop logic", so that won't do.

That leaves the use of a recursive method as a solution, similar to the attempt in the question:

static String reverseWords(String input) {
	int idx = input.indexOf(&#39; &#39;);
	if (idx == -1)
		return input;
	return reverseWords(input.substring(idx + 1)) + &#39; &#39; + input.substring(0, idx);
}

Test

System.out.println(reverseWords(&quot;Hello World&quot;));
System.out.println(reverseWords(&quot;The quick brown fox jumps over the lazy dog&quot;));

Output

World Hello
dog lazy the over jumps fox brown quick The

答案3

得分: 0

我们可以使用代码不过不是使用CharAt而是可以将它用于循环我的方法需要 `java.util.Arrays;` 来获取给定数组的子集注意你需要执行 `reverseMe(str.split(" "))` 来运行它

```java
import java.util.Arrays;

public class reverseMe {
  public String reverseMe(String[] s) {
         if(s.length == 0)
            return "";
            return s[s.length - 1] + " " + reverseMe(Arrays.copyOfRange(s,0,s.length-1));
 }
}

输入: "Hello Newer World"

输出: "World Newer Hello"


<details>
<summary>英文:</summary>

We can you use code, however instead of CharAt, we can use it for loops. My method does require `java.util.Arrays;` to get a subset of the given array. Note, you will have to do `reverseMe(str.split(&quot; &quot;))` to run it.
```java
import java.util.Arrays;

public class reverseMe {
  public String reverseMe(String[] s) {
         if(s.length == 0)
            return &quot;&quot;;
            return s[s.length - 1] + &quot; &quot; + reverseMe(Arrays.copyOfRange(s,0,s.length-1));
 }
}

Input: "Hello Newer World"

Output: "World Newer Hello"

答案4

得分: 0

因为你不能使用任何循环或反转方法,所以只能使用递归方法。
然而,这并不是非常高效。

它的工作原理是在不包括前一个字符串的最后一个单词的字符串上重复进行分割,然后返回一个新的以相反顺序排列的字符串。

ReverseMe r = new ReverseMe();
String reversed = r.reverseMe("This is a test of reversing a string");
System.out.println(reversed);

public String reverseMe(String s) {
    String arr[] = s.split("\\s+");
    if (arr.length > 1) {
        return arr[arr.length-1] + " " + reverseMe(s.substring(0, s.lastIndexOf(" ")));
    }
    return arr[arr.length-1];
}

输出结果为:

string a reversing of test a is This
英文:

Since you can't use any loops or reverse methods, that would leave a recursive method.
However, this is not very efficient.

It works by repeatedly splitting on string less the last word of the previous string and then returning a new String in reversed order.

ReverseMe r = new ReverseMe();                                                    
String reversed =r.reverseMe(&quot;This is a test of reversing a string&quot;);             
System.out.println(reversed);                                                     
                                                                                   
                                                                                      
public String reverseMe(String s) {
	String arr[] = s.split(&quot;\\s+&quot;);
	if (arr.length &gt; 1) {
		return arr[arr.length-1] + &quot; &quot; + reverseMe(s.substring(0, s.lastIndexOf(&quot; &quot;)));			  
	} 
	return arr[arr.length-1];
	
}

Prints

string a reversing of test a is This
                                                                                     

</details>



huangapple
  • 本文由 发表于 2020年8月31日 21:41:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63671941.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定