Showing posts with label two pointers. Show all posts
Showing posts with label two pointers. Show all posts

Saturday, November 7, 2015

Leetcode: Implement strStr() (4ms)

Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Subscribe to see which companies asked this question
Hide Tags
 Two Pointers String
Show Similar Problems







------------------------------------------------------------
------------------------------------------------------------
Using two pointers, but note following cases:
1. haystack = "mississippi", 
        needle = "issip";
2. haystack="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab"
    needle=    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3. when needle is longer than haystack. 

/////////////////////////////////////////////////////////////////////////////
//codes
class Solution {
 public:
        int strStr(string haystack, string needle) {
               //check input
               int len = haystack.size(), i = 0, j = 0;
               if (needle.size() == 0) return 0;
               if (len == 0 || needle.size() == 0 || len<needle.size())return -1;//case 3
               while (i<len - needle.size() + 1){ //case 2
                      if (haystack[i] != needle[j]){
                            i++;
                            continue;
                      }
                      //check needle
                      int k = i;
                      while (j<needle.size()){
                            if (haystack[k] != needle[j]){
                                   i++;//i=k;//case 1
                                   j = 0;
                                   break;
                            }
                            else{
                                   if (j == needle.size() - 1)return i;
                                   k++;
                                   j++;
                            }

                      }

               }
               return -1;
        }
 };




////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
the whole codes


#include <iostream>
using namespace std;
#include <vector>
#include <string>

class solution{
  public:
  int strstr(string& s1, string& s2){
    for(int i=0;i<s1.size();i++){
      if (s1[i]==s2[0]){
        for (int j=0;j<s2.size();j++){
          if (i+j>=s1.size() || s1[i+j]!=s2[j])break;
          if(j==s2.size()-1) return i;
        }
        
      } 
    }
    return -1;
  }
  
  
  
};

// To execute C++, please define "int main()"
int main() {
  
  solution s;
  string s1={"acbccc"}, s2={"cccc"},s3={"abc"};
  vector<string> ss;
  ss.push_back(s1);
  ss.push_back(s2);
  ss.push_back(s3);
  int res=s.strstr(s1, s2);
  cout<<"the results is: "<<res <<"\n";
  cout<<ss[0]<<ss[1] <<ss[2]<<"\n";
  

  return 0;
}

Friday, October 30, 2015

Leetcode: Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:
A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3
begin to intersect at node c1.

Notes:
  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.

-----------------------------------------
----------------------------------------
1. find the length of two lists: lenA , lenB,
(after 1, we can check whether a connection exist or not by checking the final nodes of the two lists are the same or not. If not, return directly!)
2. using two pointers pa, pb. Move the pointer forward along the longer list by abs(lenA-lenB) nodes. 
3. then move both pointers ahead step by step and check whether there is a intersection. 
NOTE 1:
 a case below:
when only one node exist and is also the intersection:
pa->[1]<-pb
NOTE 2:
when pa->NULL,
           pb->NULL,
then we have   pa==pb???. The answer is yes!!
////////////////////////////////////////////////////////////////
//codes
class Solution {
public:
       ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
              //check input
              if (headA == NULL || headB == NULL)return NULL;
              //find the length of two list
              ListNode *pa = headA, *pb = headB;
              int countA = 0, countB = 0;
              while (pa != NULL){
                     pa = pa->next;
                     countA++;
              }
              while (pb != NULL){
                     pb = pb->next;
                     countB++;
              }
              //check there are intersection or not
              if (pa != pb)return NULL;
              //move pointer forward by abs(countA-countB)
              pa = headA;
              pb = headB;
              if (countA>countB){
                     for (int i = 0; i<countA - countB; i++){
                           pa = pa->next;
                     }
              }
              else{
                     for (int i = 0; i<countB - countA; i++){
                           pb = pb->next;
                     }
              }
              //FIND THE INTERSECTION NODE
              while (pa!= NULL){
                     if (pa == pb)return pa;
                     else{
                           pa = pa->next;
                           pb = pb->next;
                     }
              }
       }
};



Thursday, October 29, 2015

Leetcode: Linked List Cycle

Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?

-----------------------------------------------------------------
-----------------------------------------------------------------
An interesting problem. 
Using two pointers: slow and fast. fast proceeds two nodes/step while slow one node/step. They will meet eventually if there is a loop inside. 
/////////////////////////////////////////////////////////////
//codes
class Solution {
public:
       bool hasCycle(ListNode *head) {
              //check input
              if (head == NULL || head->next == NULL)return false;
              //loop
              ListNode *slow = head, *fast = head;
              while (fast != NULL && fast->next != NULL){
                     fast = fast->next->next;
                     slow = slow->next;
                     if (fast == NULL)return false;
                     else if (fast == slow)return true;
              }
              return false;
       }
};

Leetcode: Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
------------------------------------------
-----------------------------------------
Just merge two sorted lists into one sorted list. Nothing special. 
/////////////////////////////////////////////////
//codes
class Solution {
public:
       ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
              //check input
              if (l1 == NULL)return l2;
              if (l2 == NULL)return l1;
              //dummy node
              ListNode*dum = new ListNode(-1), *pl1 = l1, *pl2 = l2, *p = dum;
              while (pl1 != NULL && pl2 != NULL){
                     if (pl1->val<pl2->val){
                           p->next = pl1;
                           p = p->next;
                           pl1 = pl1->next;
                     }
                     else{
                           p->next = pl2;
                           p = p->next;
                           pl2 = pl2->next;
                     }
              }
              //check left nodes and connect to p
              if (pl1 != NULL)p->next = pl1;
              else p->next = pl2;

              p = dum->next;
              delete dum;
              return p;
       }
};