Why my solution works locally but runtime error on OJ ? Last executed input:" 1 "


  • 0
    W
    class Solution {
    public:
        void reverseWords(string &s) {
            
            if (s.length() == 0)
    			return;
    			
    		//delete all leading or trailing spaces
    		string::iterator it;
    		it = s.begin();
    		while (it != s.end() && *it == ' '){
    			s.erase(it);
    		}
    		if (it == s.end())
    			return;
    		it = s.end()-1;
    		while (*it == ' '){
    			s.erase(it);
    			it--;
    		}
    		
    		//reversing
    		string::iterator beginIt;
    		s.insert(0, 1, ' ');
    		s.insert(s.end(), ' ');
    		beginIt = s.begin();
    		it = s.end() - 1;
    		while (it != beginIt){
    			if (*(it - 1) == ' '){
    			    //make sure only single space between words
    				if (*it == ' '){
    					s.erase(it);
    					it--;
    					continue;
    				}
    				while (it != s.end()){
    					s.insert(beginIt, *it);
    					beginIt++;
    					it++;
    					s.erase(it);
    				}
    			}
    			it--;
    		}
    		s.erase(s.end() - 1);
    		s.erase(s.end() - 1);
    		return;
        }
    };
    

    It's works well on my Visual Studio 2013. But failed on OJ.

    Last executed input: " 1 "

    Is there anything happen in Iterator when using "string.insert" or "string.erase"?


Log in to reply
 

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