Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@akinyeleolubodun
Last active December 6, 2016 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akinyeleolubodun/76b6927f815820565886642244d7e609 to your computer and use it in GitHub Desktop.
Save akinyeleolubodun/76b6927f815820565886642244d7e609 to your computer and use it in GitHub Desktop.
Reverse Words in a String
public class Solution {
    public String reverseWords(String s) {
        s = s.trim();
        
        List<String> spl = split(s);
        StringBuilder sb = new StringBuilder();

        for(int i = spl.size() - 1; i >= 0; i--) {
                sb.append(spl.get(i));
                sb.append(" ");
        }

        if ( sb.length() > 0 ) {
            sb.deleteCharAt(sb.length() - 1);
        }
        
        return sb.toString();
    }
    
    public static List<String> split(String string) {
        int old_posn=0,posn=0;

        List<String> str = new ArrayList<String>();

        while (posn >= 0)
        {
            posn = string.indexOf(' ',old_posn);
            String next_word = (posn>0) ?
                    string.substring(old_posn,posn):
                    string.substring(old_posn);

            if (!next_word.isEmpty()) {
                str.add(next_word);
            }

            old_posn = posn + 1;
        }

        return str;
    }
}
@oluwasayo
Copy link

Nice work!

This is the first thing that occurred to me when I saw the problem (I'm lazy). 3 milliseconds on their clock.

public class Solution {
    public String reverseWords(String s) {
        String[] arr = s.split(" ");
        StringBuilder sb = new StringBuilder();
        for (int a = arr.length - 1; a >= 0; a--) {
            if (arr[a].length() > 0) {
                if (sb.length() > 0) sb.append(" ");
                sb.append(arr[a]);
            }
        }
        return sb.toString();
    }
}

@akinyeleolubodun
Copy link
Author

@oluwasayo...I love your solution. It was the same thing I wrote that gave me 3ms. Pretty cool.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment