LeetCode 344 Reverse String

原题如下:

Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "olleh".

简单字符串翻转,直接上代码。

1     public String reverseString(String s) {
2         StringBuilder sb = new StringBuilder();
3         for (int i = s.length() - 1; i >= 0; i--) {
4             sb.append(s.charAt(i));
5         }
6         return sb.toString();
7     }

如何实现原地翻转呢?由于String不能修改,所以需要修改一下方法定义,参数使用StringBuilder。

 1     public void reverseStringInPlace(StringBuilder sb) {
 2         reverseStringInPlace(sb, 0, sb.length() - 1);
 3     }
 4 
 5     public void reverseStringInPlace(StringBuilder sb, int start, int end) {
 6         if (start >= end || end > sb.length() - 1) {
 7             return;
 8         }
 9         for (int i = start, j = end; i < j; i++, j--) {
10             char tmp = sb.charAt(i);
11             sb.setCharAt(i, sb.charAt(j));
12             sb.setCharAt(j, tmp);
13         }
14     }

这里又引出另一个问题,如何将字符串中的单词顺序翻转,但是单词本身不变?

举例:
Given s = "hello world", return "world hello".

解决方法:先对每个单词做翻转,然后对整个字符串做翻转即可。

 1     public void reverseSentenceInPlace(StringBuilder sb) {
 2         int i = 0, j = 0;
 3         for (; j < sb.length(); j++) {
 4             if (!Character.isLetter(sb.charAt(j))) {
 5                 if (i < j) {
 6                     reverseStringInPlace(sb, i, j - 1);
 7                 }
 8                 i = j;
 9                 i++;
10             }
11         }
12         if (i < j) {
13             reverseStringInPlace(sb, i, j - 1);
14         }
15         reverseStringInPlace(sb, 0, sb.length() - 1);
16     }

参考源码:https://github.com/pkufork/Martians/blob/master/src/main/java/com/pkufork/martians/leetcode/L344_ReverseString.java

原文地址:https://www.cnblogs.com/pkufork/p/ds_leetcode_344.html