Leetcode 8 Two Pointers

Two Pointers

1. 28. Implement strStr()

  用 i 记录haystack偏移量,j 记录 needle 的偏移量。

  

 1 class Solution {
 2     public int strStr(String haystack, String needle) {
 3         int lenH = haystack.length();
 4         int lenN = needle.length();
 5         if( lenN > lenH)
 6             return -1;
 7         if(lenN == 0)
 8             return 0;
 9         for(int i = 0; i <= lenH - lenN; i++){
10             boolean flag = true;
11             for(int j = 0; j < lenN; j++){
12                 if( haystack.charAt(i + j) != needle.charAt(j)){
13                     flag = false;
14                     break;
15                 }
16             }
17             if (flag)
18                 return i;
19         }
20         return -1;
21     }
22 }

2. 125. Valid Palindrome

  只需要建立两个指针,head 和 tail, 分别从字符的开头和结尾处开始遍历整个字符串,如果遇到非字母数字的字符就跳过,继续往下找,直到找到下一个字母数字或者结束遍历,如果遇到大写字母,就将其转为小写。等左右指针都找到字母数字时,比较这两个字符,若相等,则继续比较下面两个分别找到的字母数字,若不相等,直接返回false.

     Character.isLetterOrDigit ( char ).  判断是否为字符或数字

     Character.toLowercase ( char ) . 两个函数

  

 1 class Solution {
 2     public boolean isPalindrome(String s) {
 3         if( s.isEmpty())
 4             return true;
 5         
 6         int head = 0, tail = s.length() -1;
 7         char cHead, cTail;
 8         while( head <= tail){
 9             cHead = s.charAt(head);
10             cTail = s.charAt(tail);
11             if(!Character.isLetterOrDigit(cHead))
12                 head++;
13             else if(!Character.isLetterOrDigit(cTail))
14                 tail--;
15             else{
16                 if(Character.toLowerCase(cHead) != Character.toLowerCase(cTail))
17                     return false;
18             head++;
19             tail--;
20             }  
21         }
22         return true;
23     }
24 }

3. 142. Linked List Cycle II  Medium

  用快慢指针,假设有环时,head到环起点距离为A,环起点到相遇地点为B,慢指针走A+B,快指针移动距离总是慢指针两倍,且比慢指针多走一圈设为N。A+B+N = 2A + 2B。

  A = N - B。head到环起点(新设一个指针指向head) = 一圈 减去 环起点到相遇地点 = 相遇点到环起点距离。

  

 1 public class Solution {
 2     public ListNode detectCycle(ListNode head) {
 3         ListNode fast = head, slow = head;
 4         while(fast!=null && fast.next!=null){
 5             slow = slow.next;
 6             fast = fast.next.next;
 7             if( fast == slow){
 8                 slow = head;
 9                 while( slow != fast){
10                     slow = slow.next;
11                     fast = fast.next;
12                 }
13                 return fast;
14             }
15         }
16         
17         return null;
18     }
19 }

猜你喜欢

转载自www.cnblogs.com/Afei-1123/p/10776928.html