Reverse String for 3 JAVA solutions


  • 0

    Three Solutions

          class Solution {
            public String reverseString(String s) {
              if(s==null)
                return new String();
           return new StringBuilder(s).reverse().toString();
        }
    }
    
    class Solution {
        public String reverseString(String s) {
            if(s==null)
                return new String();
            char[] ch = s.toCharArray();
            int i = 0;
            int j = ch.length-1;
            while(i<j){
                char temp = ch[i];
                ch[i] = ch[j];
                ch[j] = temp;
                i++;
                j--;
            }
            return new String(ch);
        }
    }
    
    class Solution {
        public String reverseString(String s) {
            if(s==null)
                return new String();
            char[] ch = s.toCharArray();
            StringBuilder sb = new StringBuilder();
            for(int i = ch.length-1; i>=0;i--)
                sb.append(ch[i]);
            return sb.toString();
        }
    }
    

Log in to reply
 

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