My code works, but this is a horrible solution, please check String Array! HELP with better solution


  • 0
    T

    *So I used a very long string array, but I don't want to use it like I did, please suggest a alternative or how to make the array size as required *

     public class Solution {
            public String reverseWords(String s) {
                char [] original = s.toCharArray();
                String [] wordlist = new String [100000];
                String word = "";
                int index = 0;
                String rev = "";
                for(int x=0; x< original.length; x++){
                    if(original[x] != ' '){
                        word = word + original[x];
                    }
                    else if(original[x] == ' ' && word != ""){
                        wordlist[index] = word;
                        word = "";
                        index++;
                    }
                }
                if(word != ""){
                    wordlist[index] = word;
                    index++;
                }
                for(int x = index - 1; x >= 0; x--){
                    if(x == index - 1){
                    rev = wordlist[x];}
                    else{
                    rev = rev + ' ' + wordlist[x];
                }
                }
                return rev;
                }
                
                
            
        }

  • 0
    Q
    This post is deleted!

  • 0
    S

    Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example


Log in to reply
 

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