6ms easy JAVA solution


  • 2
    V

    public class Solution {

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

    }


  • 1
    J

    4ms

    new StringBuilder(s).reverse().toString()

  • 1
    K

    <!-- language-all: lang-java -->

    My 3 ms solution:

    public class Solution {
        public String reverseString(String s) {
            int n = s.length();
            char[] result = new char[n];
            char[] original = s.toCharArray();
            for(int i=0,j=n-1;i<n;i++,j--){
                result[i] = original[j];
            }
            return new String(result);
        }
    }

  • 0
    D

    what if the input is null?
    s.length() would return nullPointerException


  • 0
    T

    @dannyliufj True, but the problem statement didn't specify behaviour for that, so throwing an NPE is a valid response. This is a good example of a followup/clarifying question you would ask at an interview.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.