
Leetcode
Two Pointers
String
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(); }




近期评论