leetcode刷题---字符串---反转字符串中的单词Ⅲ

给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

示例:

输入:“Let’s take LeetCode contest”
输出:“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);
}
}

在编写的时候for循环里的第一个while循环总是会角标越界,后来决定直接用if判断解决这个问题。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-words-in-a-string-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

猜你喜欢

转载自blog.csdn.net/weixin_46428711/article/details/111152367