Skip to content

Latest commit

 

History

History
32 lines (27 loc) · 824 Bytes

151-翻转字符串里的单词.md

File metadata and controls

32 lines (27 loc) · 824 Bytes

151-翻转字符串里的单词.md

原题

给定一个字符串,逐个翻转字符串中的每个单词。 示例 1:

输入: "the sky is blue"
输出: "blue is sky the"

解法

这种问题一出来就会本能会想到要使用字符串本身的方法,但在面试的时候,肯定就会特别指出不让用 所以需要自己来实现

第一种:先用数组的方式

const reverseWords = function(words) {
    return words.split(' ').reverse().join(' ');
}

第二种,使用字符串的方式(不使用数组的 reverse 的方法

const reverseWords = function(words) {
    let res = ''
    // 先反转整个字符串
    for (let i = words.length - 1; i >= 0; i--) {
        res += words[i];
    }
}