Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

Tuesday, November 10, 2015

Leetcdoe: Longest Palindromic Substring

Difficulty: Medium
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.
Subscribe to see which companies asked this question
Hide Tags
 String
Show Similar Problems








-----------------------------------------------------------------------------------
Scan the string from left to right with the center of potential palindrome. There are two cases in this method:

case 1:
abba

case 2:
aba

Check the two cases in each scan. 

//////////////////////////////////////////
//codes
class Solution {
 public:
        string longestPalindrome(string s) {
               //check input
               if (s.size()<2)return s;
               string fnl;
               int i = 1;
               while (i<s.size()){
                      //case 1
                      int l = i, r = i;
                      while (l > -1 && r<s.size()){
                            if (s[l] == s[r]){
                                   l--;
                                   r++;
                                   continue;
                            }
                            else break;
                      }
                      ++l;
                      --r;
                      string tmp;
                      tmp.assign(s, l, r - l + 1);
                      fnl = tmp.size()>fnl.size() ? tmp : fnl;
                      

                      //case 2
                      l = i - 1, r = i;
                      while (l > -1 && r<s.size()){
                            if (s[l] == s[r]){
                                   l--;
                                   r++;
                                   continue;
                            }
                            else break;
                      }
                      ++l;
                      --r;
                      string tmp1;
                      tmp1.assign(s, l, r - l + 1);
                      fnl = tmp1.size()>fnl.size() ? tmp1 : fnl;
                      

                      //check left length
                      if (s.size() - i + 1<fnl.size() / 2)break;
                      i++;
               }
               return fnl;
        }
 };



Monday, November 9, 2015

Leetcode: Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example, 
Given s = "Hello World",
return 5.

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

///////////////////////////////////////////////
//codes
class Solution {
public:
    int lengthOfLastWord(string s) {
        //check input
        if(s.size()==0)return 0;
        int count=0,i=s.size()-1;
        //find the last non ' ' char
        for (;i>-1 && s[i]==' ';i--) continue;
        for (int j=i;j>-1 && s[j]!=' ';j--) count++;
        return count;
        }
};

Leetcode: Integer to English Words

Difficulty: Medium


Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

For example,
123 -> "One Hundred Twenty Three" 
12345 -> "Twelve Thousand Three Hundred Forty Five" 
1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Hint:
Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.

Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words.

There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)

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

According to the hints, the core is to build the help function to transfer three digits into a string. In general, there are three kinds of words for all 3-digits:

"Hundred";

 "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine ", "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen "

"Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety ";

with above words, we can build all strings for 3-digits in English. 

////////////////////////////////////////
//codes
class Solution {
 public:
        string hundred2Eng(int val){
               vector<string> v1 = { "", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine ", "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen " };
               vector<string> v2 = { "", "", "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety " };
               int hund = val / 100, ten = val % 100, dig = ten % 10;
               string res = ten<20 ? (v1[ten]) : (v2[ten / 10] + v1[dig]);
               string hud = hund == 0 ? "" : "Hundred ";
               res = v1[hund] + hud + res;
               return res;
        }

        string numberToWords(int num) {
               //check input
               if (num == 0)return "Zero";

               vector<string> v = { "Thousand ", "Million ", "Billion " };
               string res = hundred2Eng(num % 1000), tmp;
               num = num / 1000;
               for (int i = 0; i<3; i++){
                      if (num % 1000 != 0)tmp = hundred2Eng(num % (1000)) + v[i] + tmp;
                      num = num / 1000;
               }
               res = tmp + res;
               res.pop_back();//remove the final " ".
               return res;
        }
 };




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, November 6, 2015

Leetcode: Count and Say (any input)

Difficulty: Easy
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
Subscribe to see which companies asked this question
Hide Tags
 String
Show Similar Problems



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

Change this problem to: for any input not 1, like 

        string countAndSay(int n, int b) {

where b is the any input and n means output n repetitions. For example, when b=111123, the procedure
will be like following:



The whole project for above problem 
////////////////////////////////////////////////////////
//project

#include "stdafx.h"
# include <cstdlib>
#include <iostream>     // std::cout
#include <algorithm>    // std::sort
#include <vector>       // std::vector
# include <map>         // std::map
# include <unordered_map>
# include <string>
#include <bitset>
#include <ctype.h>
#include <sstream>
using namespace std;


 class Solution {
 public:
        string countAndSay(int n, int b) {
               string final;
               //check input
               //if(n==NULL)retun final;
               final += to_string(b);
               final += ", ";
               string tmp = to_string(b), tmpStore;
               char digi = tmp[0];
               for (int i = 0; i<n; i++){
                      int count = 0,j=0;
                      //
                      for (; j<tmp.size(); j++){
                            if (tmp[j] != digi || j==tmp.size()){
                                   final += to_string(count);
                                   final += tmp[j-1];
                                   //store current string
                                   tmpStore += to_string(count);
                                   tmpStore += tmp[j-1];
                                   //adjust the parameters
                                   count = 0;
                                   digi = tmp[j];
                                   j--;
                            }
                            else{
                                   count++;
                            }
                      }
                      //put on the lefts
                      final += to_string(count);
                      final += tmp[j-1];
                      tmpStore += to_string(count);
                      tmpStore += tmp[j-1];
                      final += ", ";
                      //adjust the parameters
                      tmp = tmpStore;
                      tmpStore.clear();
                      digi = tmp[0];
                      cout << final << endl;
               }
               //remove last ", "
               final.erase(final.end() - 2, final.end());
               return final;
        }
 };

int main(int argc, char *argv[])

{

       Solution s;
       string outt = s.countAndSay(10,22);

}