Java Solution


  • 0
    U
    public class Solution {
        public String reverseString(String str) {
            int i=0;
            int j = str.length()-1;
            char[] chars = str.toCharArray();
            while(i<j) {
                char c = chars[i];
                chars[i] = chars[j];
                chars[j] = c;
                i++;
                j--;
            }
            return new String(chars);
        }
        public String reverseWords(String s) {
            if(s==null) {
                return null;
            }
            String[] strs = s.split(" ");
            int spaceCount = strs.length - 1;
            StringBuilder reverseStr = new StringBuilder();
            
            for(int i=0; i<strs.length; i++) {
                String subStr = reverseString(strs[i]);
                reverseStr.append(subStr);
                if(spaceCount !=0) {
                    reverseStr.append(" ");
                    spaceCount--;
                }
            }
            return reverseStr.toString();
            
        }
    }
    

Log in to reply
 

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