回文链表、字符串压缩
- 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;
}
};
- 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;
}
};