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;
    }
  • 相关阅读:
    mysql 常用命令行
    mysql常用命令
    Mac os安装wget
    linux下给文件夹或者目录赋权
    Python学习相关资料
    Mac常用的一些操作
    Mac os安装git及 git及githup的使用
    Linux磁盘占用100%解决方法
    page-break-after:always
    工具
  • 原文地址:https://www.cnblogs.com/linwx/p/7750463.html
Copyright © 2011-2022 走看看