Last active
January 3, 2016 08:09
-
-
Save codebynumbers/8433806 to your computer and use it in GitHub Desktop.
Java port of Python gist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class WordLimit { | |
| public static void main(String args[]) { | |
| assert(limit("cat dog", 3) == "cat"); | |
| assert(limit("cat", 3) == "cat"); | |
| assert(limit("cat ", 4) == "cat"); | |
| assert(limit("cat dog", 5) == "cat"); | |
| assert(limit("cat dog bird", 10) == "cat dog"); | |
| assert(limit("cat", 9) == "cat"); | |
| } | |
| public static String limit(String s, int max) { | |
| if (s.length() <= max) { | |
| return s; | |
| } | |
| for (int i=max-1; i >= 0; i--) { | |
| if (s.charAt(i) == ' ') { | |
| max = i; | |
| break; | |
| } | |
| } | |
| return s.substring(0, max); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment