首页 > 其他 > 详细

【剑指offer】一些简单题05 06

时间:2021-01-14 22:15:33      阅读:40      评论:0      收藏:0      [点我收藏+]

剑指offer一些简单题

05 替换空格

题目

请实现一个函数,把字符串 s 中的每个空格替换成"%20"。

思考

  • 直接遍历,遇到空格就更改

代码

class Solution {
public:
    string replaceSpace(string s) {
        string ans = "";
        for(int i=0;i<s.size();i++)
        {
            if(s[i]==‘ ‘)   ans+="%20";
            else    ans+=s[i];
        }
        return ans;
    }
};

06 从尾到头打印链表

题目

  • 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

思考

  • 注意vector 有库函数reverse!!

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> vec;
        while(head){
            vec.push_back(head->val);
            head = head->next;
        }
        reverse(vec.begin(),vec.end());
        return vec;
    }
};

【剑指offer】一些简单题05 06

原文:https://www.cnblogs.com/xuwanwei/p/14279104.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!