LeetCode 344. Reverse String

Topic description

  • LeetCode 344. Reverse String
  • Please write a function whose function is to reverse the input string.

Example

  • Input: s = "hello"
  • returns: "olleh"

Code

  • Java

    class Solution {
        public String reverseString(String s) {
            if (s == null || s.length() <= 1) {
                return s;
            }
            char[] arr = s.toCharArray();
            int length = arr.length;
            for (int i = 0; i < length / 2; i++) {
                char temp = arr[i];
                arr[i] = arr[length - i - 1];
                arr[length - i - 1] = temp;
            }
            return String.valueOf(arr);
    
            //return new StringBuilder(s).reverse().toString();
        }
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325295901&siteId=291194637