Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
Given s = "hello", return "olleh".
Solution 1:
Approach: use StringBuilder.reverse() method
public class Solution {
public String reverseString(String s) {
StringBuilder sb=new StringBuilder(s);
return sb.reverse().toString();
}
}
Solution 2:public class Solution {
public String reverseString(String s) {
StringBuilder sb=new StringBuilder();
for(int i=s.length()-1; i>=0; i--){
sb.append(s.charAt(i));
}
return sb.toString();
}
}
No comments:
Post a Comment