Special Reverse - Reverse words in the input string but escape the HTML encodings...


  • 0
    M

    I used a simple Stack to reverse the words but escape those HTML encodings...
    Assumption was that words were separated by space

    package interview.indeed;
    
    import java.util.Stack;
    @author: muthuk
    public class  ReverseSpecial{
    	private Stack<Character> dataStack;
    
    	public ReverseSpecial(){
    		dataStack = new Stack<Character>();
    	}
    
    	public void addWord(String input_string , boolean escape){
    		if(!escape){
    			char[] inputchars = input_string.toCharArray();
    			for(int i=0;i<inputchars.length ;i++){
    				dataStack.push(inputchars[i]);
    			}
    		}else{
    			char[] inputchars = input_string.toCharArray();
    			for(int i=inputchars.length-1;i>=0 ;i--){
    				dataStack.push(inputchars[i]);
    			}
    
    		}
    		dataStack.push(' ');//Split the words ...would need a rtrim to restore...
    	}
    
    
    	public String toString(){
    		StringBuilder build= new StringBuilder();
    		while(dataStack.size()>0){
    			build.append(dataStack.pop());
    		}
    		return build.toString();
    	}
    
    
    
    
    	public static void main(String... args){
    		String test1= "ABCD ;amp;#32; PQRS";
    		String test2= "PQRS ;amp;#32; ABCD RACECAR";
    		ReverseSpecial mnode = new ReverseSpecial();
    		String[] words=test2.split(" ");
    		for(int w=0;w<words.length;w++){
    			if((words[w].startsWith(";",0)) && (words[w].endsWith(";")))
    				mnode.addWord(words[w], true);
    			else {
    				mnode.addWord(words[w], false);
    			}
    		}
    
    		System.out.println(mnode.toString());
    
    	}
    
    }
    
    
    
    

Log in to reply
 

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