|  | 
|  | 1 | +package me.ramswaroop.strings; | 
|  | 2 | + | 
|  | 3 | +import java.util.Arrays; | 
|  | 4 | + | 
|  | 5 | +/** | 
|  | 6 | + * Created by IntelliJ IDEA. | 
|  | 7 | + * | 
|  | 8 | + * @author: ramswaroop | 
|  | 9 | + * @date: 10/25/15 | 
|  | 10 | + * @time: 9:44 PM | 
|  | 11 | + */ | 
|  | 12 | +public class RemoveExtraSpaces { | 
|  | 13 | + | 
|  | 14 | +    /** | 
|  | 15 | +     * Removes extra spaces in string {@param s} without creating a | 
|  | 16 | +     * extra variable to hold the result, in O(n) time complexity. | 
|  | 17 | +     * | 
|  | 18 | +     * @param s | 
|  | 19 | +     * @return | 
|  | 20 | +     */ | 
|  | 21 | +    public static String removeExtraSpaces(String s) { | 
|  | 22 | +        char[] c = s.toCharArray(); | 
|  | 23 | + | 
|  | 24 | +        int j = c.length; | 
|  | 25 | +        for (int i = 1; i < c.length; i++) { | 
|  | 26 | +            // check for two or more consecutive spaces | 
|  | 27 | +            if (c[i] == ' ' && c[i - 1] == ' ') { | 
|  | 28 | +                // if extra spaces encountered for the 1st time | 
|  | 29 | +                if (j == c.length) j = i; | 
|  | 30 | + | 
|  | 31 | +                // skip all extra spaces | 
|  | 32 | +                while (i < c.length && c[i] == ' ') { | 
|  | 33 | +                    i++; | 
|  | 34 | +                } | 
|  | 35 | +                 | 
|  | 36 | +                // if reached end of string then stop | 
|  | 37 | +                if (i == c.length) break; | 
|  | 38 | +            } | 
|  | 39 | + | 
|  | 40 | +            // copy characters occurring after extra spaces to their appropriate positions | 
|  | 41 | +            while (i < c.length && j < c.length) { | 
|  | 42 | +                if (c[i] == ' ' && c[i - 1] == ' ') break; | 
|  | 43 | + | 
|  | 44 | +                c[j] = c[i]; | 
|  | 45 | +                i++; | 
|  | 46 | +                j++; | 
|  | 47 | +            } | 
|  | 48 | +        } | 
|  | 49 | + | 
|  | 50 | +        return String.valueOf(Arrays.copyOf(c, j)); | 
|  | 51 | +    } | 
|  | 52 | + | 
|  | 53 | +    public static void main(String a[]) { | 
|  | 54 | +        System.out.println(removeExtraSpaces("ram swaroop is a good boy.")); | 
|  | 55 | +        System.out.println(removeExtraSpaces("ram swaroop      is      a    good boy.")); | 
|  | 56 | +        System.out.println(removeExtraSpaces("ram swaroop      is      a    good    boy    .")); | 
|  | 57 | +        System.out.println(removeExtraSpaces("   ram swaroop      is      a    good boy    .")); | 
|  | 58 | +    } | 
|  | 59 | +} | 
0 commit comments