Java formatting str with regular expression


  • 0

    The formatting is the essence of the problem compared with version II. Replace contiguous white spaces with
    only one space.

    public class Solution {
        public String reverseWords(String str) {
            char[] format = str.trim().replaceAll("\\s+", " ").toCharArray();
            int n = format.length;
            reverse(format, 0, n - 1);
            int j = 0;
            for (int i = 0; i < n; i++) {
                if (format[i] == ' ') {
                    reverse(format, j, i - 1);
                    j = i + 1;
                }
            }
            reverse(format, j, n - 1);
            return new String(format);
        }
        
        private void reverse(char[] format, int start, int end) {
            for (int i = start, j = end; i < j; i++, j--) {
                char tmp = format[i];
                format[i] = format[j];
                format[j] = tmp;
            }
        }
    }
    

Log in to reply
 

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