Is using Java's StringTokenizer considered cheating?


  • 0
    Q
    public class Solution {
        public int lengthOfLastWord(String s) {
            if (s == null){
                return 0;
            }
            s = new StringBuilder(s).reverse().toString();
            java.util.StringTokenizer t = new java.util.StringTokenizer(s, " ");
            if (t.hasMoreTokens()){
                String last = t.nextToken();
                return last.length();
            }
            return 0;
        }
    }

  • 0
    L

    I have the same concern, i use Regex to split the Strings makes this too easy...

    This is how I did:

     public class Solution {
        public int lengthOfLastWord(String s) {
            String[] words = s.split("\\s+");
            if(words.length==0)
                return 0;
            return words[words.length-1].length();
        }
    }

Log in to reply
 

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