Reverse words in a sentence.


  • 1
    G

    Given a sentence, like 'MyNameIsTom'.Yeah, there is no space in the sentence. And also given a big dictionary that contains all the words. Please write a function to find out those word and reverse it . So the result should be 'yMemaNsImoT'.


  • 0
    T
    This post is deleted!

  • 0
    T
    import java.util.*;
    
    public class ReverseString {
    	static Set<String> dict = new HashSet<String>();
    
    	void revert(String input) {
    		Stack<String> s = new Stack<String>();
    		revertInt(input, s);
    	}
    
    	void revertInt(String input, Stack<String> result) {
    		if (input.length() == 0) {
    			System.out.println("Find one result:");
    			for (String s : result) {
    				System.out.print(revertWord(s));
    			}
    			System.out.println("\n");
    		}
    		for (int i = 1; i <= input.length(); i++) {
    			String substr = input.substring(0, i);
    			if (dict.contains(substr)) {
    				result.push(substr);
    				revertInt(input.substring(i), result);
    				result.pop();
    			}
    		}
    	}
    
    	String revertWord(String word) {
    		String s = "";
    		for (int i = 0; i < word.length(); i++) {
    			s += word.charAt(word.length() - i - 1);
    		}
    		return s;
    	}
    
    	public static void main(String[] args) {
    		ReverseString.dict.add("MyName");
    		ReverseString.dict.add("My");
    		ReverseString.dict.add("Name");
    		ReverseString.dict.add("Is");
    		ReverseString.dict.add("Tom");
    		ReverseString.dict.add("IsTom");
    
    		ReverseString a = new ReverseString();
    		a.revert("MyNameIsTom");
    	}
    }
    

  • 0
    G

    public static void main(String[] args) {

    	String sentence = "MyNameIsTom";
    	String[] dic = {"My","Name","Is","Tom"};
    	String rev = "";
    	for(int i =0; i < dic.length; i++) {
    		
    		if(sentence.indexOf(dic[i]) >= 0) {
    			
    			StringBuilder sb = new StringBuilder(dic[i]);
    			rev = rev + sb.reverse().toString();
    		}
    	}
    	System.out.println(rev);
    	
    
    }
    

    }


Log in to reply
 

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