Skip to content

Latest commit

 

History

History
81 lines (64 loc) · 1.68 KB

20210112.md

File metadata and controls

81 lines (64 loc) · 1.68 KB

Algorithm

557. Reverse Words in a String III

Description

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.

Solution

class Solution {
    public String reverseWords(String s) {
        String[] strings = s.split("\\s+");
        StringBuffer result = new StringBuffer();
        for(int i=0;i<strings.length;i++){
            if(i==strings.length-1){
                result.append(new StringBuffer(strings[i]).reverse());
            }else{
                result.append(new StringBuffer(strings[i]).reverse()).append(" ");
            }
        }
        return result.toString();
    }
}
public String reverseWords(String s) {
    String[] words = s.split(" ");
    StringBuilder sb = new StringBuilder();
    for(String word:words){
        sb.append(new StringBuffer(word).reverse().toString() + " ");
    }
    return sb.toString().trim();
}
class Solution {
   public String reverseWords(String s) {
		char[] ca = s.toCharArray();
		for(int i=0;i<ca.length;i++) {
			if(ca[i]!=' ') {
				int j = i;
				while(j+1<ca.length&&ca[j+1]!=' ') {j++;}
				reverse(ca,i,j);
				i=j;
			}
		}
		return new String(ca);
	}
	private void reverse(char[] ca, int i,int j) {
		for(;i<j;i++,j--) {
			char temp = ca[i];
			ca[i] = ca[j];
			ca[j] = temp;
		}
	}
}

Discuss

Review

Tip

Share