zoukankan      html  css  js  c++  java
  • Reverse Words in a String III

    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.

    思考:

      1.如何找到空格位置?

      2.如何截断字符串并把它旋转?

    思路:可以用start和end变量找到并控制空格位置,然后再用循环把字符串逆序。

    解法一: 用JavaScript内置方法

    /**
     * @param {string} s
     * @return {string}
     */
    var reverseWords = function(s) {
        var str = s.split(" ");  //截断成数组
        for(let i=0;i<str.length;i++){
            str[i] = str[i].split("").reverse().join(""); //把各子字符串截断为数组,再逆转,再拼成字符串
        }
        return str.join(" ");  //再用空格分开字符串
    };

    解法二:C语言

    char* reverseWords(char* s) {
        int i=0,j=0;
        int start=0,end=0;
        int len=strlen(s);
        char temp;
        for(i=0;i<=len;i++){
            if(s[i]==' '||s[i]==''){  //找到空格位置
                 end=i-1;
                int result = end+start;
                 for(j=start;j<=result/2;j++){   //旋转字符串
                     temp=s[j];
                     s[j]=s[result-j];
                     s[result-j]=temp;
                 }  
                 start=i+1;
            }
        }
        return s;
    }
  • 相关阅读:
    Windows Python+Eclipse环境配置
    infobright系列二:数据迁移
    infobright系列一:源码安装infobright
    autotools归纳
    Atlas系列一:Atlas功能特点FAQ
    C#反射技术概念作用和要点
    .net获取本机公网IP代码
    Java泛型-类型擦除
    现在就使用HTML5的十大原因
    让网页图片变灰色的三种方法
  • 原文地址:https://www.cnblogs.com/linwx/p/7750463.html
Copyright © 2011-2022 走看看