美文网首页
557. Reverse Words in a String I

557. Reverse Words in a String I

作者: clshinem | 来源:发表于2017-04-18 22:27 被阅读0次

    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.

    c语言实现

    char* reverseWords(char* s) {
        int start = 0;
        // char temp;
        int len = strlen(s); //这个不放在外面就会超时
        for(int i = 0;i<=len;i++){//注意这里的i<=strlen(s) 对于一个字符串的最后一位是'\0'所以下标要多,才能遍历到那一位
            if(s[i] == ' ' || s[i] == '\0'){
                int end = i-1;
                int size = (start + end) / 2;
                for(int j = start;j <= size;j++){ //双数的是要小于等于
                    char temp = s[j];
                    s[j] = s[end];
                    s[end] = temp;
                    end = end -1;
                }
                start = i + 1;
            }
        }
        return s;
    }
    

    遇到一个问题,之前是for (int i = 0;i<=strlen(s);i++)
    提交之后报超时,放在外面就不报了,不知到为啥····
    python实现

    class Solution(object):
        def reverseWords(self, s):
            """
            :type s: str
            :rtype: str
            """
            a = s.split(' ')
            b = []
            for i in a:
                b.append(i[::-1])
            c = ' '.join(b) 
            return str(c)
    

    写完之后发现和刘老师写的一样,厉害了
    第一次提交出错,是用了 return str(b)
    循环之后 b 变为['god', 'sevol', 'gip']
    str(b) "['god', 'sevol', 'gip']"
    然后查了下list怎么变str
    但是str变list

    >>>str = 'abcde'
    >>>a = list(str)
    >>>a
    >>>['a','b','c','d','e']
    

    相关文章

      网友评论

          本文标题:557. Reverse Words in a String I

          本文链接:https://www.haomeiwen.com/subject/mcwqzttx.html