def reverse(s:str) ->str:
# 递归
if s is None or len(s) <= 1:
return s
return reverse(s[1:]) + s[0]
def reverse_loop(s:str) ->str:
# 迭代
l = list(s)
from_ ,to = 0, len(l) -1
while from_ < to:
l[from_],l[to] = l[to],l[from_]
from_ += 1
to -= 1
return "".join(l)
def reverse_api(s:str) ->str:
if s is None or len(s) <= 1:
return s
return s[::-1]
if __name__ == '__main__':
print(reverse_api("中文内容如下"))
func main() {
fmt.Println(reverse("中文的内容如下"))
}
func reverse(s string) string {
// 递归
runes := []rune(s)
if len(runes) <= 1 {
return string(runes)
}
return string(runes[1:]) + string(runes[0])
}
func reverseLoop(s string) string {
// 迭代
runes := []rune(s)
from := 0
to := len(runes) - 1
for from < to {
runes[from], runes[to] = runes[to], runes[from]
from ++
to --
}
return string(runes)
}
package com.test;
public class Reverse {
public static void main(String[] args) {
System.out.println(reverse("abcdefghijklmn"));
}
private static String reverse(String s) {
// 递归
if ((null == s) || (s.length() <= 1)) {
return s;
}
return reverse(s.substring(1)) + s.charAt(0);
}
private static String reverseLoop(String s) {
// 迭代
// StringBuffer sb = new StringBuffer();
// for (int i=s.length()-1;i>=0;i--){
// sb.append(s, i, i+1);
// }
// return sb.toString();
char[] chars = s.toCharArray();
int from = 0;
int to = s.length() -1;
char tmp;
while (from < to) {
tmp = chars[from];
chars[from] = chars[to];
chars[to] = tmp;
from ++;
to --;
}
return String.valueOf(chars);
}
private static String reverseAPI(String s) {
// 调用 java api 速度快,效率高
if ((null == s) || (s.length() <= 1)) {
return s;
}
return new StringBuffer(s).reverse().toString();
}
}