面经--逆转字符串

[面经] 逆转字符串(Java)

如何逆转字符串呢?本篇介绍几种常见方法:

  1. 暴力解法
  2. StringBuilder自带的reverse
  3. reverse源码
  4. 堆栈
  5. 集合的reverse方法
暴力解法: 利用String.charAt(),倒序地访问 原String的各个char
1
2
3
4
5
6
7
8
9
10
public static String reverseIt(String source) {
int i, len = source.length();
StringBuilder dest = new StringBuilder(len);

for (i = (len - 1); i >= 0; i--){ // key
dest.append(source.charAt(i));
}

return dest.toString();
}
最不装的:直接利用自带reverse方法
1
new StringBuilder(hi).reverse().toString()
这显然没什么营养,我们看看StringBuilder的reverse()做了什么:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static String reverse(String input){
char[] in = input.toCharArray();
int begin=0;
int end=in.length-1;
char temp;
while(end>begin){ // key
temp = in[begin];
in[begin]=in[end];
in[end] = temp;
end--;
begin++;
}
return new String(in);
}
当然,如果你想被嫌弃,也可以用堆栈:
1
2
3
4
5
6
7
8
9
10
11
12
public String reverseString(String s) {
Stack<Character> stack = new Stack<Character>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
stack.push(s.charAt(i));
}
while (!stack.empty()) { // key
sb.append(stack.pop());
}
return sb.toString();

}
或者想被喷出翔,装一下箱,拆一下箱:
1
2
3
4
5
6
7
8
9
10
11
12
public static void reverseStr(String input){
char[] hello = input.toCharArray();
List<Character> trial1 = new ArrayList<>();

for (char c: hello)
trial1.add(c);

Collections.reverse(trial1); // key
ListIterator li = trial1.listIterator();
while (li.hasNext())
System.out.print(li.next());
}

Powered by KyleCe

Copyright © 2015 - 2019 KyleCe All Rights Reserved.

访客数 : | 访问量 :