简体   繁体   English

递归方法将字符串中的每个字母向后打印3次

[英]Recursive method print each letter in a string 3 times backwards

I'm working on a recursive method that will return and print in my main method, each letter of a string three backwards. 我正在开发一种递归方法,该方法将在我的main方法中返回并打印,字符串的每个字母向后三个。 The string being (args[1]). 字符串为(args [1])。 So for instance, if the string is "stack". 因此,例如,如果字符串是“ stack”。 It should output to: 它应该输出到:

kkkcccaaatttsss kkkcccaaatttsss

So far I managed to print the string backwards. 到目前为止,我设法将字符串向后打印。 How should I go about printing each string three times? 我应该如何将每个字符串打印三遍?

My code so far: 到目前为止,我的代码:

public static void main(String[] args){
    int number = Integer.parseInt(args[0]);
    String word = new String("");
    word = args[1];

    String methodddd = recursive1.method4(word, number);
    System.out.println(methodddd);
}

public static String method4(String word){
    int length = word.length();
    if (length == length*3){
     return "";
    }
    return word.substring(length-1, length) +  method4(word.substring(0, length-1));
}

You are very close: modify the return line to pre-pend substring three times, instead of pre-pending it once: 您非常接近:将return行修改为在子字符串之前添加三次,而不是在其之前添加一次:

public static String method4(String word){
    int length = word.length();
    if (length == 0){
         return "";
    }
    String last = word.substring(length-1, length);
    return  last + last + last +  method4(word.substring(0, length-1));
}

Note the ending condition: length == length*3 is true if (and only if) length is zero. 注意结束条件: length == length*3当(且仅当) length为零时为true。

Demo. 演示。

Here's the basic answer, in pseudocode: 这是伪代码的基本答案:

recursive_stutter(s:string){
   if length of s is 0
      return
   letter = s[0]    // save the first character
   recursive_stutter(s from 1 to length)
   printf "%c%c%c",letter, letter,  letter
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM