My 2ms Java Solution, No split()


  • 0
    A
    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;
        }
    }
    

Log in to reply
 

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