1.回文字符串
回文辫塌,英文palindrome活鹰,指一個順著讀和反過來讀都一樣的字符串哈恰,比如madam、我愛我志群,這樣的短句在智力性着绷、趣味性和藝術(shù)性上都頗有特色,中國歷史上還有很多有趣的回文詩锌云。
那么荠医,我們的第一個問題就是:判斷一個字串是否是回文?
思路:
前后兩邊逐個對比
2. 單向鏈表判斷回文
判斷一條單向鏈表是不是“回文”
思路:
1.用快慢指針宾抓,定位到中間節(jié)點
2.把前半段逆轉(zhuǎn)方向
3.注意單個節(jié)點的鏈表子漩,奇偶長度的鏈表
private static boolean isPalindromeList( Node node ){
if( node == null ){
return false;
}
if( node.next == null ){
return true;
}
Node slow = node;
Node fast = node;
boolean isDouble = true;
while( true ){
if( fast.next == null ){
isDouble = false;
break;
}
fast = fast.next;
if( fast.next == null )
{
break;
}
else{
fast = fast.next;
}
slow = slow.next;//slow每次走一步
}
//這是slow就是中點
Node center = slow;
Node head2 = center.next;
//把前半段,逆轉(zhuǎn)順序石洗,如果是奇數(shù)幢泼,則前半段不包含slow;如果是偶數(shù)讲衫,則前半段包含slow
Node head = node;
Node curr = head.next;
Node temp;
head.next = null;
while( curr != null ){
if( isDouble ){
if( head == center ){
break;//偶數(shù)長度缕棵,末尾
}
}
else if( curr == center ){
break;//奇數(shù)長度,末尾
}
temp = head;
head = curr;
curr = curr.next;
head.next = temp;
}
Node head1 = head;
while( head1 != null ){
if( head1.value != head2.value ){
return false;
}
head1 = head1.next;
head2 = head2.next;
}
return true;
}