short java code without explanation


  • 17
        public String reverseWords(String s) {
            String[] str = s.split(" ");
            for (int i = 0; i < str.length; i++) str[i] = new StringBuilder(str[i]).reverse().toString();
            StringBuilder result = new StringBuilder();
            for (String st : str) result.append(st + " ");
            return result.toString().trim();
        } 
    

  • 0
    T

    kind of the same idea:

    public String reverseWords(String s) {
    	        StringBuilder sb1 = new StringBuilder();
    	        StringBuilder sb2 = new StringBuilder();
    	        char[] a = s.toCharArray();
    	        for(int i = 0; i<a.length;i++){
    	        	if(a[i] != ' '){
    	        		sb1.append(a[i]);
    	        	}else{
    	        		sb2.append(sb1.reverse().toString());
    	        		sb1.setLength(0);
    	        		sb2.append(" ");
    	        	}
    	        }
    	        sb2.append(sb1.reverse().toString());
    	        return sb2.toString();
    	 }

  • 0
    T

    @Yang_BU

    I to chose to use the functions inherent to StringBuilder.

    class Solution {
    public String reverseWords(String s) {

        StringBuilder sb = new StringBuilder();
        String[] arr = s.split(" ");
        
        for (String word : arr) {
            StringBuilder temp = new StringBuilder(word);
            sb.append(temp.reverse());
            sb.append(" ");
        }
        return sb.toString().trim();
    }
    

    }


Log in to reply
 

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