Monday, November 25, 2013

Day 54 # 29, Divide Two Integers

Divide Two Integers
Divide two integers without using multiplication, division and mod operator. 
-----------------------------------------------------------------
keep multiplying divisor by 2 until divisor is larger than dividend, then divide it by 2
compute the difference between divisor and dividend, set it as the new dividend


class Solution {
public:
    int divide(int dividend, int divisor) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        
        long long a = abs((double)dividend);;
        long long b = abs((double)divisor);
        int sign = 1;
        if (dividend < 0) sign *= -1; 
        if (divisor < 0) sign *= -1; 
        
        int total = 0; 
        while (a >= b) {
            long long c = b;
            int count = 1;
            while (a >= (c<<1)) {
                c = c << 1;
                count = count << 1;
            }
            a = a - c;
            total += count;
        }
        return total*sign;
    }
};

Java, updated on Aug-6th-2018
原来同上,就是不断的对以下数组里的数进行循环相减,然后更新被除数
[divisor * 2, divisor * 2 ^ 2, divisor * 2 ^ 3, divisor * 2 ^ 4 ...]
注意处理溢出

class Solution {
    public int divide(int dividendInt, int divisorInt) {
        
        long dividend = Math.abs((long)dividendInt);
        long divisor = Math.abs((long)divisorInt);
        
        int sign = 1;
        if (dividendInt < 0) sign *= -1;
        if (divisorInt < 0) sign *= -1;
        
        long count = 0;
        while (dividend >= divisor) {
            int tempCount = 1;
            long tempDivisor = divisor;
            while ((tempDivisor << 1) < dividend) {
                tempCount <<= 1;
                tempDivisor <<= 1;
            }
            
            dividend -= tempDivisor;
            count += tempCount;
        }
        
        if (count > Integer.MAX_VALUE) {
            if (sign == 1) return Integer.MAX_VALUE;
            return Integer.MIN_VALUE; 
        }
        
        return (int) count * sign;
    }
}

Friday, November 22, 2013

Day 53, 28, Implement strStr()

Implement strStr()
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
------------------------------------------------- 
KMP, O(n),
class Solution {
public:
    vector<int> computePrefixTable(string pattern) {
        int m = pattern.length();
        vector<int> table(m,0);
        int matchedLength = 0;
        
        for (int i = 1; i < m; i++) {
            // until find the next char at matchedLength is equal to char at i
            // or matchedLength is zero
            while (matchedLength > 0 && pattern[matchedLength] != pattern[i]) {
                matchedLength = table[matchedLength - 1];
            }
            if (pattern[matchedLength] == pattern[i]) {
                matchedLength++;
            }
            table[i] = matchedLength;
        }
        
        return table;
    }
    
    int KMP(string source, string pattern) {
        int n = source.length();
        int m = pattern.length();
        vector<int> table = computePrefixTable(pattern);
        int matchedLength = 0;
        
        for (int i = 0; i < n; i++) {
            while (matchedLength > 0 && pattern[matchedLength] != source[i]) {
                matchedLength = table[matchedLength - 1];
            }
            
            if (pattern[matchedLength] == source[i]) {
                matchedLength++;
            }
            if (matchedLength == m) {
                return i - m + 1;
            }
        }
        
        return -1;
    }

    int strStr(string haystack, string needle) {
        if (needle == "") return 0;
        if (haystack == "") return -1;
        return KMP(haystack,needle);
    }
};
Solution #2 O(m*n), improved brute force
class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if (*needle == NULL) return haystack;
        if (!*haystack) return NULL;
        char* adv = haystack;
        char* temp = needle;
        while (*++temp) {
            adv++;
        }
        
        while (*adv != NULL) {
            char* itr1 = haystack;
            char* itr2 = needle;
            while (*itr1 && *itr2 && *itr1 == *itr2) {
                itr1++;
                itr2++;
            }
            if (!*itr2) return haystack;
            haystack++;
            adv++;
        }
        return NULL;
    }
};

Wednesday, November 20, 2013

Day 52, 25, Reverse Nodes in k-Group

Reverse Nodes in k-Group
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
---------------------------------------------------------------------
Iterative, similar toDay 42, #92 Reverse Linked List II
How to tackle this using recursion? Later !!!
-- relax, it is easy,

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if (k == 1) return head;
        if (head == NULL || head->next == NULL) return head;
        ListNode *newHead = head,*itr = head, *tail = NULL;
        int count = 0;
        while(itr != NULL) {
            itr = itr->next;
            count++;
            if (count == k) {
                ListNode* newTail = newHead, *itr2 = newHead;
                newHead = tail;
                while (count > 0) {
                    ListNode* next = itr2->next;
                    itr2->next = newHead;
                    newHead = itr2;
                    itr2 = next;
                    count--;
                }
                if (tail == NULL) {
                    head = newHead;
                }else  tail->next = newHead;
                newTail->next = itr2;
                tail = newTail;
                newHead = itr2;
            }
        }
        return head;
    }
};
Update on Feb-06-2015
Using dummy node
class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        if (k <= 1 || head == NULL) return head;
        ListNode *dummy = new ListNode(0);
        dummy->next = head;
        ListNode *pre = dummy;
        
        int count = 0;
        while (head != NULL) {
            count++;
            
            if (count == k) {
                // reverse
                ListNode *newHead = NULL, *itr = pre->next, *tempNext = head->next;
                while (itr != tempNext) {
                    ListNode *temp = itr->next;
                    itr->next = newHead;
                    newHead = itr;
                    itr = temp;
                }
                ListNode *tail = pre->next;
                pre->next = newHead;
                pre = tail;
                tail->next = tempNext;
                head = tempNext;
                count = 0;
            }else
                head = head->next;
        }
        
        return dummy->next;
    }
};

Tuesday, November 19, 2013

Day 51, #5, Longest Palindromic Substring(*) ATTENTION NEEDED

Longest Palindromic Substring
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
 -------------------------------------------
Solution#1 O(n^2),
there are (2n - 1) centers for all possible palindromes
class Solution {
public:
    void pal (string s, int &left, int &right, int &maxLeft,int &maxRight) {
        while (left >= 0 && right < s.length()) {
            if (s[left] == s[right]) {
                left--;
                right++;
            }else {
                break;
            }
        }
        if (maxRight - maxLeft < right - left - 2) {
                maxLeft = left + 1;
                maxRight = right - 1;
        }
    }

    string longestPalindrome(string s) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if (s.length() == 1) return s;
        int maxLeft = 0;
        int maxRight = 0;
        int center = 1;
        int max = 0;
        for (;center < s.length(); center++) {
            int left = center - 1;
            int right = center;
            pal(s,left,right,maxLeft,maxRight); // even
            left = center - 1;;
            right = center + 1;
            pal(s,left,right,maxLeft,maxRight); // odd
        }
        return s.substr(maxLeft,maxRight - maxLeft + 1);
    }
};


Solution#2 O(n) 
http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
Jun-27-2015
Manacher's algorithm

class Solution {
public:
    string processString(string s) {
        if (s.length() == 0) return s;
        string rt = "";
        for (int i = 0; i < s.length(); i++) {
            rt = rt + "#" + s[i];
        }
        rt += '#';
        return rt;
    }

    string longestPalindrome(string s) {
        string t = processString(s);
        vector<int> p(t.length(),0);
        int center = 1, rightExpand = 1;
        
        for (int i = 1; i < t.length(); i++) {
            int i_mirror = center - (i - center); 
            if (rightExpand > i) {
                p[i] = min(rightExpand - i,p[i_mirror]);
            }
            
            while (i + 1 + p[i] > 0 && i + 1 + p[i] < t.length() && t[i + 1 + p[i]] == t[i - 1 - p[i]]) {
                cout << p[i] << endl;
                p[i]++;
            }
            
            if (i + p[i] > rightExpand) {
                rightExpand = i + p[i];
                center = i;
            }
        }
        
        int longest = 0;
        int index = 0;
        for (int i = 0; i < p.size(); i++) {
            if (longest < p[i]) {
                index = i;
                longest = p[i];
            }
        }
        return s.substr((index - longest) / 2, longest);
    }
};