A string of the written interview questions

Source: Internet
Author: User

Maximum subsequence

The largest subsequence is to find the largest continuous subsequence in a one-dimensional array consisting of numbers. For example, the maximum subsequence of {5,-3, 4, 2} is {5,-3, 4}, and its sum is 8 to reach the maximum; while {5,-6, 4, the maximum subsequence of 2} is {4, 2}, and its sum is 6. As you can see, the method for finding the largest subsequence is very simple. As long as the sum of the first I items is not less than 0, the subsequence will be extended backward, otherwise, discard the previous sub-sequence to start a new sub-sequence. At the same time, we need to write down the sum of the sub-sequences, and finally find and the largest sub-sequence.

# Include <iostream> using namespace STD; int maxsubseq (const int * arr, int Len, int * Start, int * End) {int max = 0; // record the largest subsequence currently found and INT sum = 0; // record the current subsequence and INT begin = 0, finish = 0; // record the starting subscript * Start = begin; * end = finish; // record the starting subscript of the oldest sequence for (INT I = 0; I <Len; I ++) {sum + = arr [I]; finish = I; If (sum> MAX) {max = sum; * end = finish; * Start = begin ;} if (sum <= 0) {sum = 0; begin = I + 1 ;}} return Max ;}int main () {int arr [6] = {5, -3,-2, 12, 9,-1}; int start, end; int max = maxsubseq (ARR, 6, & START, & End ); cout <"The maxsubseq is from position" <start <"to position" <End <". "<Endl; cout <" sum of masubseq: "<max <Endl; return 0 ;}

Longest Common substring (LCS)

Find the longest common substring of two strings, which must be continuous in the original string. In fact, this is a sequential decision-making problem, which can be solved using dynamic planning. We use a two-dimensional matrix to record the result in the middle. How to construct this two-dimensional matrix? For example: "Bab" and "Caba" (of course, we can see at a glance that the longest public substring is "ba" or "AB ")

B A B

C 0 0 0

A 0 1 0

B 1 0 1

A 0 1 0

We can see that the longest diagonal line of the matrix can find the longest common substring.

However, finding the longest diagonal line composed of 1 on a two-dimensional matrix is also time-consuming. The following improvements: when the matrix is filled with 1, make it equal to the element in the upper left corner of the matrix plus 1.

B A B

C 0 0 0

A 0 1 0

B 1 0 2

A 0 2 0

In this way, the maximum element in the matrix is the length of the longest common substring.

In the process of constructing the two-dimensional matrix, the previous row of the matrix is useless because a row of the matrix is obtained. In fact, the one-dimensional array can be used in the program to replace the matrix.

# Include <iostream> # include <cstring> # include <vector> using namespace STD; // str1 is horizontal, str2 is vertical const string LCS (const string & str1, const string & str2) {int xlen = str1.size (); // horizontal length vector <int> TMP (xlen ); // Save the upper row of the matrix vector <int> Arr (TMP); // The current row int ylen = str2.size (); // The vertical length int maxele = 0; // maximum value of the matrix element int Pos = 0; // the maximum value of the matrix element appears in the column for (INT I = 0; I <ylen; I ++) {string S = str2.substr (I, 1); arr. assign (xlen, 0); // array clear 0 (Int J = 0; j <xlen; j ++) {If (str1.compare (J, 1, S) = 0) {If (j = 0) arr [J] = 1; else arr [J] = TMP [J-1] + 1; if (ARR [J]> maxele) {maxele = arr [J]; pos = J ;}}// {// vector <int>: iterator iter = arr. begin (); // while (ITER! = Arr. end () // cout <* ITER ++; // cout <Endl; //} TMP. assign (ARR. begin (), arr. end ();} string res = str1.substr (POS-maxele + 1, maxele); Return res;} int main () {string str1 ("21232523311324 "); string str2 ("312123223445"); string LCS = LCS (str1, str2); cout <LCS <Endl; return 0 ;}

Longest Common subsequence

The difference between the longest common sub-sequence and the longest common sub-string is that the longest common sub-sequence does not need to be continuous in the original string. For example, the longest public sub-sequence of Ade and ABCDE is Ade.

We use the dynamic planning method to solve this problem. First, find the state transition equation:

In the equal sign convention, C1 is the rightmost character of S1, C2 is the rightmost character of S2, and S1 'is the part that removes C1 From S1, s2 'is the part that removes C2 from S2.

LCS (S1, S2) is equal to the following three items:

(1) LCS (S1, S2 ')

(2) LCS (S1 ', S2)

(3) LCS (S1 ', S2') -- If C1 is not equal to C2; LCS (S1 ', S2') + C1 -- If C1 is equal to C2;

Boundary termination condition: If S1 and S2 are both empty strings, the result is also empty strings.

Next we also need to build a matrix to store the solutions to the neutron problems in the dynamic planning process. Each number in this matrix represents the length of the row and the LCS before the column. In contrast to the status transition agenda just analyzed above, the number in each grid in the matrix should be filled in as follows, which is equal to the maximum value of the following three items:

(1) numbers in the above Grid

(2) number in a cell on the left

(3) number in the upper-left pane (if C1 is not equal to C2); Number + 1 in the upper-left pane (if C1 is equal to C2)

# Include <iostream> # include <cstring> # include <stack> # include <utility> # define leftup 0 # define left 1 # define up 2 using namespace STD; int max (int A, int B, int C, int * max) {// the highest priority for A and the lowest priority for C. the maximum value is saved in * max. Int res = 0; // the cell in which the res record comes * max = A; If (B> * max) {* max = B; res = 1;} If (C> * max) {* max = C; Res = 2;} return res ;} // when calling this function, please pay attention to assigning a long string to str1, which is mainly used to save time in the time of backtracking the largest sequence. If a long string is not assigned to str1, the proper execution of the program is not affected. String LCS (const string & str1, const string & str2) {int xlen = str1.size (); // horizontal length int ylen = str2.size (); // If (xlen = 0 | ylen = 0) // if either of str1 and str2 is null, return NULL return "; pair <int, int> arr [ylen + 1] [xlen + 1]; // construct a pair two-dimensional array, first record data, second record source for (INT I = 0; I <= xlen; I ++) // The first line clears 0 arr [0] [I]. first = 0; For (Int J = 0; j <= ylen; j ++) // clear 0 arr for the first column [J] [0]. first = 0; For (INT I = 1; I <= ylen; I ++) {char S = str2.at (I-1); For (Int J = 1; j <= x Len; j ++) {int leftup = arr [I-1] [J-1]. first; int left = arr [I] [J-1]. first; int up = arr [I-1] [J]. first; If (str1.at (J-1) = s) // C1 = c2 leftup ++; int Max; arr [I] [J]. second = max (leftup, left, up, & arr [I] [J]. first); // cout <arr [I] [J]. first <arr [I] [J]. second <"" ;}// cout <Endl ;}/ * matrix constructed * // trace back to find the longest common subsequence stack <int> st; int I = ylen, j = xlen; while (! (I = 0 & J = 0) {If (ARR [I] [J]. second = leftup) {If (ARR [I] [J]. first = arr [I-1] [J-1]. first + 1) ST. push (I); -- I; -- J;} else if (ARR [I] [J]. second = left) {-- J;} else if (ARR [I] [J]. second = up) {-- I;} string res = ""; while (! St. empty () {int Index = ST. top ()-1; Res. append (str2.substr (index, 1); ST. pop ();} return res;} int main () {string str1 = "gccctagcg"; string str2 = "gcgcaatg"; string LCS = LCS (str1, str2 ); cout <LCS <Endl; return 0 ;}

Exact string matching BM algorithm

The so-called exact string matching problem is to find all the substrings that exactly match query P in text T. The BM algorithm can effectively solve this problem and reduce the time complexity to a lower level than the linear level.

The BM algorithm mainly uses three clever and effective methods: scanning from right to left, bad character rules, and good suffix rules.

Scan from right to leftIt means to start from the last character and match forward, rather than from the beginning and back.

Bad character rulesYes. Ti is different from PJ during the scan from right to left. If a PK is the same as Ti in P, and k <I will directly shift P to the Right to align the PK WITH Ti, and then match from right to left. If P does not contain any characters of the same ti, the first character of P is directly aligned with the next character of Ti and then compared from right to left.

T: a B c B A D f t a T E

P: C B A X A D

P: C B A X A D

Use R (X) to represent the rightmost position of character X in P. In this example, R (B) = 2.

We can see that using the right-to-left scan and bad character rules can skip many positions in T without checking, so that the time complexity is lower than linear.

Suffix rulesYes. During the scanning process from right to left, we found that Ti is different from PJ. Check whether the same part of T appears in the other position of P,) if t is different from T, P is shifted to the right to align T with T in T. B) If t' does not appear, find the longest prefix of P with the same suffix as t, and move P to the right so that X corresponds to the suffix of T in T.

A ):

N: 1

N: 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8

T: a B c B a d f t B c a q v t B C E...

P: C B C A B C E A B C

P: c B c a B c e a B C f

Obviously, it is not to align P to the Right to align P5 with T9, but to align P2 with T9 because P1 and P8 are different. Use L (I) to represent the maximum position of t'. In this example, L (9) = 3.

B ):

N: 1

N:

1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8

T: a B c B a d f t B c a q v t B C E...

P: B C A B C E T B C

P: B C A B C E T B C

It can be seen that when P cannot find "TBC" to the left, the suffix of "TBC" that matches the longest prefix of P is found, and P is shifted to the right. Use L (I) to indicate the length of the longest suffix. In this example, I = 8.

[Preprocessing] input the query string P, calculate the L (I) and L (I) at each position in P, and calculate R (I ). [Query] K: = N; // n is the total number of characters in T while K <= m do begin I: = N; // I represents the position H of the characters in P: = K; // H indicates the character position in T while I> 0 and P (I) = T (I) Do begin I: = I-1; H: = h-1; end; if I = 0 then begin outputs the string at this position of T; k: = K + N-l (2); End else moves P (increase K ), k. The maximum end value determined by the suffix rule and the bad character rule;

String Copy Function

# Include "stdafx. H "using namespace STD;/** Note: String Copy * parameter: DEST target address, SRC Source Address * return: Copied address; if an error or overlap exists, undefined * exception: string overflow may occur, and the space occupied by DEST is not as large as that occupied by Src. */Char * strcpy (char * DEST, const char * SRC) {// when debugging, assert (DEST! = NULL) & (SRC! = NULL); // note that the memory points to the memory where the Dest parameter is located, rather than the stack memory. Therefore, char * To = DEST can be returned in the function; // The main operation is to complete while in the while condition (* DEST ++ = * SRC ++ )! = '\ 0 ');
// Return the first address of the copy string for convenient concatenation, such as strlen (strcpy (DEST, "hello") Return-1 ;}

Reverse string output

General Method

#include <stdio.h>#include <string.h>void StringReverse(char *str){if(NULL == str){return ;}char *pBegin = str;char *pEnd   = str + strlen(str) - 1;while(pBegin < pEnd){char tmp = *pBegin;*pBegin = *pEnd;*pEnd = tmp;pBegin ++, pEnd --;}}int main(){char str[] = "123456789";StringReverse(str);printf("%s\n",str);}

Linked List

void PrintListReversely(ListNode* pListHead)  {        if(pListHead != NULL)        {              // Print the next node first              if (pListHead->m_pNext != NULL)              {                    PrintListReversely(pListHead->m_pNext);              }                 // Print this node              printf("%d", pListHead->m_nKey);        }  }  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.