Leetcode brushing questions---string---reverse words in string Ⅲ

Given a string, you need to reverse the character order of each word in the string, while still preserving the initial order of spaces and words.

Example:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

class Solution {
    
    
    public String reverseWords(String s) {
    
    
    char[] chs=s.toCharArray();
    int start=0;int end=0;

    for(int i=0;i<chs.length;i++){
    
    
        start=i;
        while(chs[i]!=' '&&i<chs.length-1){
    
    
        end=i;
        i++;
        }
        if(i==chs.length-1)end++;
        while(start<end){
    
    
            char temp=chs[start];
            chs[start]=chs[end];
            chs[end]=temp;
            start++;
            end--;
        }
    }

    return new String(chs);
}
}

At the time of writing, the first while loop in the for loop would always be out of bounds. Later, I decided to use if judgment to solve this problem.

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/reverse-words-in-a-string-iii The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/weixin_46428711/article/details/111152367