Java Solutions with Only two pointers


  • 0
    public class Solution {
        public String reverseWords(String s) {
            if (s == null || s.length() == 0) {
                return s;
            }
            StringBuilder sb = new StringBuilder();
            int i = s.length() - 1;
            while (i >= 0) {
                while(i >= 0 && s.charAt(i) == ' ') {
                    i--;
                }
                int end = i;
                if (end >= 0 && sb.length() > 0) {
                    sb.append(' ');
                }
                while (i >= 0 && s.charAt(i) != ' ') {
                    i--;
                }
                int start = i;
                sb.append(s.substring(start + 1, end + 1));
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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