LeetCode-回文链表的判断

编写一个函数,检查输入的链表是否是回文的。

我的思路:

1.如果能知道长度的话,就可以把前半段链表倒置,然后与后半段依次判断。

2.直接把整个链表倒置,再依次比对,但时间复杂度满足不了O(n)。

/**
 * 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) return true;
        ListNode* t = head;
        ListNode* reverse = new ListNode(head->val);
        reverse->next = NULL;
        t=t->next;
        while(t){
            ListNode* temp = new ListNode(t->val);
            temp->next=reverse;
            reverse=temp;
            t=t->next;
        }
        while(reverse){
            if(reverse->val != head->val){
                return false;
            }
            head=head->next;
            reverse=reverse->next;
        }
        return true;
    }
};

官方答案:

把链表中的值保存在一个数组中,再判断转置的数组与原数组是否相等。

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        vals = []
        current_node = head
        while current_node is not None:
            vals.append(current_node.val)
            current_node = current_node.next
        return vals == vals[::-1]

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/palindrome-linked-list-lcci/solution/hui-wen-lian-biao-by-leetcode-solution-6cp3/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

这个方法可以延伸到很多地方,值得一记。

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

2021 / 9 / 16 更新

关于C++中字符串反转的操作

1.reverse(iterator begin, iterator end)

需要调用 algorithm库

#include <iostream>
#include <math.h>
#include <string>
#include <algorithm>

using namespace std;

int main() {
	int a, b;
	cin >> a >> b;
	int temp = a + b;
	int temp1 = abs(temp);
	string result;
	int countt = 0;
	if (temp1 ==0) {
		result += '0';
	}
	else {
		while (temp1 >= 1) {
			char ch = (temp1 % 10) + '0';
			result += ch;
			temp1 /= 10;
			countt++;
			if (countt % 3 == 0) {
				result += ',';
				countt = 0;
			}
		}
	}
	
	
	if (temp < 0) {
		cout << '-';
	}
	if (result[result.length()-1] == ',') {
		result.erase(result.length()-1);
	}
	//for (int i = result.length() - 1; i >= 0; i--) {
	//	cout << result[i];
	//}
     reverse(result.begin(), result.end());
	cout << result;
	return 0;
}

  

posted @ 2021-03-08 16:05  徐不二  阅读(75)  评论(0)    收藏  举报