Tuesday, August 25, 2015

Leetcode: Valid Palindrome (12ms)(string)(two pointers)

PROBLEM:
https://leetcode.com/problems/valid-palindrome/



-----------------------------------------------------------

See what's Palindrome here. Basically means that you can read forwards or backward and you get the same thing, like: level.

Two pointers.
Transform all into lower case first, then process one by one.

//////////////////////////////////////////////////////////////////
// codes
class Solution {
public:
       bool isPalindrome(string s) {
              int len = s.size(), l = 0, r = len - 1;
              //check input
              //if (len <= 1) return true;
              //transform to the lower case
              for (int i = 0; i < len; i++){
                     if (s[i] >= 'A' && s[i] <= 'Z')
                           s[i] = s[i] + 32;
              }
              while (l<r){
                     while (l<len){
                           if (s[l] >= 'a' && s[l] <= 'z' || s[l] >= '0' && s[l] <= '9')break;
                           else l++;
                           if (l == len)return true;
                     }
                     while (r>-1){
                           if (s[r] >= 'a' && s[r] <= 'z' || s[r] >= '0' && s[r] <= '9')break;
                           else r--;
                           //if(r==-1)return true;
                     }
                     if (s[l] != s[r])return false;
                     l++;
                     r--;
              }
              return true;
       }

};

Leetcode: Valid Parentheses (0ms)(string)(stack)

PROBLEM:
https://leetcode.com/problems/valid-parentheses/

--------------------------------

1. using stack to temporally store the characters;
2. when meet [, {, (, push to stack;
3. when meet }, ], ), compare with the top of stack;
        if it's a pair, pop the top one (delete the top one);
        if it's not a pair, it's failed. 
4. if in the final, nothing it's left, it's true. 

See codes for details. 



/////////////////////////////////////////////////////////
// codes 0ms
class Solution {
public:
       bool isValid(string s) {
              stack<char> sta;
              sta.push('0');
              for (auto c : s){
                     switch (c) {
                     case '{':
                           sta.push('{');
                           break;
                     case '}':
                           if (sta.top() != '{') return false;
                           else sta.pop();
                           break;
                     case '[':
                           sta.push('[');
                           break;
                     case ']':
                           if (sta.top() != '[') return false;
                           else sta.pop();
                           break;
                     case '(':
                           sta.push('(');
                           break;
                     case ')':
                           if (sta.top() != '(') return false;
                           else sta.pop();
                           break;
                     default:;
                     }
              }
              if (sta.top() == '0')return true;
              else return false;
       }

};

Monday, August 24, 2015

Leetcode: Minimum Window Substring (hash table)(two pointers)

PROBLEM:
https://leetcode.com/problems/minimum-window-substring/



----------------------------------
The general idea is to use map and two pointers. Use two pointer to form a sliding window while the value between is processed through a map, or hash table.

1. we build a map, tMap, for t;
2. using two pointers: left and right to form a windon:
3.  when moving right we do
       tMap[s[r]]--; 
    for each step, until all value in tMap is <=0;

4.  then moving left until any value in tMap reaches 1, which means the current minimal window is found.

5. repeat until the end.


  ////////////////////////////////////////////////////////////////////
// codes
class Solution {
public:
       string minWindow(string s, string t) {

              unordered_map<char, int> tMap;
              int ss = s.size(), st = t.size();
              //check input
              if (ss<st)return "";

              for (int i = 0; i<st; i++){
                     tMap[t[i]]++;
              }
              //search
              int l = 0, r = 0, lflag = 0, rflag = 1, count = 0, sm = tMap.size();
              int a[3] = { ss + 1, 0, ss + 1 };
              while (r<ss + 1 && count <= st){
                     //move right
                     if (rflag == 1){
                           tMap[s[r]]--;
                          
                           if (tMap[s[r]] == 0)count++;//counted when an item is removed
                           if (count == sm){//check whether all items in t have been found
                                  lflag = 1;
                                  rflag = 0;
                           }
            r++;
                     }
                     //move left
                     if (lflag == 1){
                           tMap[s[l]]++;
                     //when any value reaches 1, that means current minimal window is reached
                           if (tMap[s[l]] == 1){
                                  if (r - 1 - l + 1<a[2]){
                                         a[0] = l; a[1] = r - 1; a[2] = r - 1 - l + 1;
                                  }
                                  lflag = 0;
                                  rflag = 1;
                                  count--;
                           }
                           l++;
                     }
                     //when to jump out
                     if (r == ss && count<sm)break;
              }

              if (a[0] == ss + 1)return "";
              else{
                     string res(s, a[0], a[2]);
                     return res;
              }

       }

};

Friday, August 21, 2015

Leetcode: Repeated DNA Sequences (hash table) (bit operation)

Problem:

https://leetcode.com/problems/repeated-dna-sequences/

-----------------------------------------------


1. Using map only:

build a frequency map using method from:

Leetcode: Substring with Concatenation of All Words (hash table)


And the result codes are:

////////////////////////////////////////////////////////
// codes 
class Solution {
public:
       vector<string> findRepeatedDnaSequences(string s) {
              vector<string> res;
              map<string, int> mapTmp;
              int n = s.size();
              if (n<10)return res;
              for (int i = 9; i<n; i++){
                     string sTmp;
                     sTmp.assign(s, i - 9, 10);
                     if (++mapTmp[sTmp] == 2) res.push_back(sTmp);
              }
              return res;
       }
};

==> memory exceeded!!!


2. How to minimize the memory used? using bit operation:

defind:
A -> 00
C -> 01
G -> 10
T -> 11
the substring with 10 characters can be transformed to a int. 
with this transformation and follow the method in 1, we have the code:

/////////////////////////////////////////////
//codes
class Solution {
private:
       int sToInt(string sTmp){
              int m = sTmp.size(), n = 0;
              for (int i = 0; i<m; i++){
                     int code = 0;
                     //coding for each character
                     switch (sTmp[i]){
                     case 'A':
                           code = 0; break;
                     case 'C':
                           code = 1; break;
                     case 'G':
                           code = 2; break;
                     case 'T':
                           code = 3; break;
                     default:;
                     }
                     n = n | code;
                     n=n << 2;
              }
              return n;
       }
public:
       vector<string> findRepeatedDnaSequences(string s) {
              vector<string> res;
              map<int, int> mapTmp;
              int n = s.size();
              if (n<10)return res;
              for (int i = 9; i<n; i++){
                     string sTmp;
                     sTmp.assign(s, i - 9, 10);
                     int k = sToInt(sTmp);//transform string to int
                     if (++mapTmp[k] == 2) res.push_back(sTmp);
              }
              return res;


       }
};



Wednesday, August 19, 2015

Leetcode: Substring with Concatenation of All Words (hash table)(string)solution

PROBLEM:
https://leetcode.com/problems/substring-with-concatenation-of-all-words/


This problem is designed for using hash table. Other kinds of smarter methods exist, but it will take a long time to figure it out, at least for me. So here I focus on the general method, hash table.

the method using here is very similar to following problem in this post:

Leetcode: Valid Anagram (hash table)(sort)

At first, we build a map for the words with repeating frequency, the second value of the map is the occurrence frequency:

see the following two methods to build the frequency map:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1.
              map<string, int> w;
              for (int i = 0; i<words.size(); i++){
                     //if exist already
                     if (w.find(words[i]) != w.end()){
                           w[words[i]]++;
                     }
                     else w[words[i]] = 1;
              }

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2.

              for (int i = 0; i<words.size(); i++){
                    w[words[i]]++;
               }
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Apparently, the second method is better. We don't need to identify whether the item we want to add exist in map or not. Why? Please refer to reference somewhere. 


The second step is to check the string s from left to right one by one. What i'm using here is to minus the frequency in map w, until all is 0, which means we find one. Or if the frequency value become negative or we can't find the item in map w, break the loop and continue the next one. ....

////////////////////////////////////////////////////////////////////////////
class Solution {
public:
       vector<int> findSubstring(string s, vector<string>& words) {
              int n = words[0].size(), m = words.size(), len = s.size();
              map<string, int> w;
              vector<int> res;
              //build map for words, duplication should be considered!
              for (int i = 0; i<words.size(); i++){
                     w[words[i]]++;
              }

              //search in the dictionary, s.
              int th1 = len - m*n + 1, th2 = (m - 1)*n;
              for (int i = 0; i<th1; i++){
                     map<string, int> wTmp = w;
                     int j = i;
                     while (j - i <= th2 && j<len){
                           string tmp;
                           tmp.assign(s, j, n);

                           if (w.find(tmp) == w.end()) break;
                           else wTmp[tmp]--;
                           //check negative
                           if (wTmp[tmp]<0)break;
                           //check success or not
                           if (j - i == th2) {
                                  res.push_back(i);
                                  break;
                           }
                           j += n;
                     }
              }
              return res;
       }
};