【问题标题】:How to put the char with the smallest ASCII value at the end of the String recursively?如何递归地将具有最小 ASCII 值的字符放在字符串的末尾?
【发布时间】:2018-05-29 14:51:55
【问题描述】:

给定方法:

public String moveSmallest(String s) {}

如何找到具有最小 ASCII 值的字符,将其放在字符串的末尾,并返回该字符串,递归

阅读Find a char..Move the char..Move to end.. 并没有真正回答:我需要什么算法,如何实现。

不能使用全局变量、累加器、辅助方法或任何其他结构。

这个问题与How to pass a partial solution to the next recursive call密切相关(本质上)。

尝试查找最小字符:

    if (s.length() == 0) {
        return s;
    } else if (s.length() > 1) {
        char c = s.charAt(0) > moveSmallest(s.substring(1)).charAt(s.length()-1) ? s.charAt(0) : moveSmallest(s.substring(1)).charAt(s.length()-1);    
    }

【问题讨论】:

  • 你尝试过什么吗?

标签: java string recursion


【解决方案1】:

好吧,如果你真的想使用递归,就在这里。

将最小的字母移到末尾:

public static String moveSmallestToTheEnd(String s) {
    if (s.length() <= 1)
        return s;
    if (s.length() == 2)
        return s.charAt(0) < s.charAt(1) ? String.valueOf(s.charAt(1)) + s.charAt(0) : s;

    String suffix = s.substring(1);
    String res = moveSmallestToTheEnd(suffix);
    return s.charAt(0) < res.charAt(res.length() - 1) ? suffix + s.charAt(0) : s.charAt(0) + res;
}

输出:

a -> a
ab -> ba
ba -> ba
abc -> bca
bac -> bca
bca -> bca
bcdae -> bcdea
bcae -> bcea

将最高字母移到开头:

public static String moveHighestToTheBeginning(String s) {
    if (s.length() <= 1)
        return s;
    if (s.length() == 2)
        return s.charAt(0) < s.charAt(1) ? String.valueOf(s.charAt(1)) + s.charAt(0) : s;

    String prefix = s.substring(0, s.length() - 1);
    String res = moveHighestToTheBeginning(prefix);
    return s.charAt(s.length() - 1) > res.charAt(0) ? s.charAt(s.length() - 1) + prefix : res + s.charAt(s.length() - 1);
}

输出:

a -> a
ab -> ba
ba -> ba
abc -> cab
bac -> cba
bca -> cba
bcdae -> ebcda
bcae -> ebca

【讨论】:

  • @Dallmayer Das is sehr einfach!
猜你喜欢
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
  • 2014-03-11
  • 2023-01-27
  • 1970-01-01
  • 2014-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多