2020-09-30刷题

回文链表、字符串压缩

  1. leetcode-面试题02.06-回文链表
    题型:双指针、栈
    难度:简单
    题目:编写一个函数,检查输入的链表是否是回文的。
    代码:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(head==nullptr || head->next==nullptr) return true;
        ListNode *pFast = head;
        ListNode *pSlow = head;
        stack<ListNode *> sk;
        while(pSlow && pFast && pFast->next)
        {
            sk.push(pSlow);
            pFast = pFast->next->next;
            pSlow = pSlow->next;
        }
        if(pFast != nullptr)
        {
            pSlow = pSlow->next;
        }
        while(!sk.empty())
        {
            pFast = sk.top();
            sk.pop();
            if(pSlow->val == pFast->val)
            {
                pSlow = pSlow->next;
            }
            else
            {
                return false;
            }
        }
        return true;
    }
};
  1. leetcode-面试题01.06-字符串压缩
    题型:字符串
    难度:简单
    题目:字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。
    代码:
class Solution {
public:
    string compressString(string S) {
        int n = S.size();
        if(n == 0) return S;
        string res = "";
        int count = 1;
        int index = 0;
        int i=1;
        while(i < n)
        {
            if(S[i] == S[index])
            {
                count++;
                i++;
            }
            else
            {
                string tempstr = "";
                while(count > 0)
                {
                    int num = count%10;
                    count /= 10;
                    char ch = num+'0';
                    tempstr = ch+tempstr;
                }

                
                res += S[index];
                res += tempstr;
                count = 1;
                index = i;
                i++;
            }
        }
        string tempstr = "";
        while(count > 0)
        {
            int num = count%10;
            count /= 10;
            char ch = num+'0';
            tempstr = ch+tempstr;
        }   
        res += S[index];
        res += tempstr;
        if(res.size() >= n)
            return S;
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值