Palindrome Linked List:
O(n)时间复杂度和O(1)空间复杂度,所以要翻转链表(一开始没想到),翻转链表用了迭代法。
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) {
return true;
}
ListNode * slow, *fast,*ptmp;
ptmp=slow = fast = head;
while (fast && fast->next) {
slow = slow->next;
if (fast->next->next == NULL)
ptmp = fast->next;
fast = fast->next->next;
}
if (fast) {
reverseList(slow->next, fast);
//slow = slow->next;
while (slow&&fast) {
if (head->val != fast->val) {
return false;
}
fast = fast->next;
head = head->next;
}
}
else {
reverseList(slow, ptmp);
while (slow&&ptmp) {
if (head->val != ptmp->val) {
return false;
}
ptmp = ptmp->next;
head = head->next;
}
}
return true;
}
ListNode* reverseList(ListNode* pNode, ListNode* header)
{
if (pNode == NULL || pNode->next == NULL)
{
header = pNode;
return pNode;
}
else
{
ListNode* pTempNext = reverseList(pNode->next, header);
pNode->next = NULL;
pTempNext->next = pNode;
return pNode;
}
}
};
Longest Common Prefix:
做这道题的时候想的很笨,就是一个一个遍历比较,嵌套了三个for(auto it = vector.begin();it!=vector.end();it++)这样的循环,逻辑复杂不说,还得处理空字符串、空向量等许多特殊情况,暴露了我过分依赖STL库和算法优化敏感度不高的缺陷。最后还是用了网上的一份代码,主要思路是:
2个字符串的最长公共前缀,其长度肯定不会超过最短的字符串的长度,设最短的字符串长度为n,那么只要比较这2个字符串的前n个字符即可。如此得出这2个字符串的最长公共前缀prefix后,再拿prefix作为新的字符串和数组中的下一个字符串比较,方法同上。需要注意的是,如果数组中的某个字符串长度为0,或者求得的当前最长公共前缀的长度为0,就直接返回空字串。
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (strs.size() == 0)
return "";
string prefix = strs[0];
for (int i = 1; i < strs.size(); ++i)
{
if (prefix.length() == 0 || strs[i].length() == 0)
return "";
int len = prefix.length() < strs[i].length() ? prefix.length() : strs[i].length();
int j;
for (j = 0; j < len; ++j)
{
if (prefix[j] != strs[i][j])
break;
}
prefix = prefix.substr(0,j);
}
return prefix;
}
};