题解 | #牛群编号的回文顺序#
牛群编号的回文顺序
https://www.nowcoder.com/practice/e41428c80d48458fac60a35de44ec528
考察的知识点:回文的判断、链表;
解答方法分析:
- 首先,将链表节点的值转换为字符串的过程可以使用循环遍历链表的方式,逐个将节点的值添加到字符串中。
- 接着,可以使用双指针的方式,一个指针指向字符串的开头,另一个指针指向字符串的末尾,依次比较对应位置的字符,如果发现不相等的字符,则不是回文串,返回
false
。 - 如果遍历结束,都没有发现不相等的字符,则说明是回文串,返回
true
。
所用编程语言:C++;
完整编程代码:↓
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return bool布尔型 */ bool isPalindrome(ListNode* head) { if (head == nullptr || head->next == nullptr) { return true; } string str = ""; while (head != nullptr) { str += to_string(head->val); head = head->next; } for (int i = 0; i < str.length() / 2; i++) { if (str[i] != str[str.length() - i - 1]) { return false; } } return true; } };