[关闭]
@XQF 2018-03-07T22:59:03.000000Z 字数 1057 阅读 789

如何实现字符串的反转?

数据结构与算法


1.低级反转

I love you------>uoy evol I

  1. public class Solution {
  2. public String reserve(String string) {
  3. if(string=null){
  4. return null;
  5. }
  6. char[] chars = string.toCharArray();
  7. for (int i = 0; i < chars.length / 2; i++) {
  8. swap(chars, i, chars.length - 1 - i);
  9. }
  10. return new String(chars);
  11. }
  12. public void swap(char[] chars, int i, int j) {
  13. char temp = chars[i];
  14. chars[i] = chars[j];
  15. chars[j] = temp;
  16. }
  17. public static void main(String[] args) {
  18. Solution solution = new Solution();
  19. String string = "I love you";
  20. System.out.println(solution.reserve(string));
  21. }
  22. }

2.高级反转

I love you -->you love I
换汤不换药

  1. public class Solution {
  2. public String reserve(String string) {
  3. if (string == null || string.length() == 0) {
  4. return null;
  5. }
  6. String[] strs = string.split(" ");
  7. for (int i = 0; i < strs.length / 2; i++) {
  8. swap(strs, i, strs.length - 1 - i);
  9. }
  10. StringBuffer sb = new StringBuffer();
  11. for (int i = 0; i < strs.length; i++) {
  12. sb.append(strs[i] + " ");
  13. }
  14. return sb.toString();
  15. }
  16. public void swap(String[] strs, int i, int j) {
  17. String temp = strs[i];
  18. strs[i] = strs[j];
  19. strs[j] = temp;
  20. }
  21. public static void main(String[] args) {
  22. Solution solution = new Solution();
  23. String string = "I love you";
  24. System.out.println(solution.reserve(string));
  25. }
  26. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注