• 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;
    }
  • 相关阅读:
    selenium-web自动化,常用api
    jmeter利用bean shell加密解密方法
    http请求属性说明(基础篇)
    移动端候选人面试要点
    CssSelector定位详解
    下载zip文件
    BeanShell生成随机中文字符
    BeanShell生成随机字符
    CentOS 7.2安装Oracle19C
    Centos7.4部署onlyoffice文档在线编辑服务器
  • 原文地址:https://www.cnblogs.com/linwx/p/7750463.html
Copyright © 2020-2023  润新知