Skip to content

Latest commit

 

History

History
46 lines (35 loc) · 735 Bytes

344. Reverse String.md

File metadata and controls

46 lines (35 loc) · 735 Bytes
title toc date tags top
344. Reverse String
false
2017-10-30
Leetcode
Two Pointers
String
344

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

Example 1:

Input: "hello"
Output: "olleh"

Example 2:

Input: "A man, a plan, a canal: Panama"
Output: "amanaP :lanac a ,nalp a ,nam A"

分析

循环

public String reverseString(String s) {
    StringBuilder res = new StringBuilder();
    for (int i = s.length() - 1; i >= 0; i--) {
        res.append(s.charAt(i));
    }
    return res.toString();
}

直接利用StringBuilder.reverse()方法。

public String reverseString(String s) {
    return new StringBuilder(s).reverse().toString();
}