Some problems in C-language string arithmetic problem solving example summary _c language

Source: Internet
Author: User
Tags arithmetic first string strlen

A string problem is a recurring problem in an interview, and there are a number of problems that are difficult to disagree with. The following is a few strings of the topic, online can find solutions, their realization for a moment, for netizens reference. Sensory algorithm is important to have the right ideas, the realization is not a problem. You must think more, so the harvest may be a little more.

Question 1:Find the longest common substring of two strings.
Specifically, if all characters in a string are in the order in which they appear in the string, then a string called a substring of string two. Note that characters that do not require substring (string one) must appear consecutively in string two. Write a function that enters two strings, asks for their longest common substring, and prints out the longest common substring.
Thought: The algorithm book generally has the introduction, is uses the dynamic planning the thought. The key is to find the optimal substructure property, which is more difficult. Another frequently asked question, "the maximum and the number of sub arrays", is also the idea of dynamic programming. The core of the longest common substring of two strings is finding the optimal substructure.
Set sequence x = {x1,x2,... xm} and y = {y1,y2,... yn} 's longest common substring is z = {z1,z2,... ZK}, then
1 if xm= yn and zk=xm=yn, then Zk-1 is the longest common substring of Xm-1 and Yn-1
2 if Xm!=yn and ZK!=XM, Z is the longest common substring of Xm-1 and y
3 if Xm!=yn and Zk!=yn, Z is the longest common substring of x and Yn-1
where xm-1= {x1,x2,..., xm-1},yn-1 = {Y1,y2,..., yn-1}zk-1 = {z1,z2,... zk-1}
With this relationship, it is easy to get a recursive formula. Record the result with a two-dimensional array R, where Z[i][j] represents the longest common substring length of Xi and YJ.
(1) If i = 0 or j = 0,z[i][j] = 0
(2) If Xi and YJ are equal, z[i][j] = z[i-1][j-1] + 1
(3) If Xi and YJ are not equal, z[i][j] = max{z[i-1][j],z[i][j-1]}
Basically, but the title requires that the longest common substring be printed, as long as an array R records the process of getting the longest common substring, where r[i][j] indicates the value of the z[i][j] is the solution of which child problem.
Reference code:

function function: Print the longest common substring//function parameter: X for the source string 1,y for the source string 2,r for the record, row for R, Col for R's column coordinates//return value: Empty void lcs_print (const char *X, const 
    char *y, int **r, int row, int col) {if (r[row][col] = = 1) {lcs_print (X, Y, R, Row-1, COL-1);  cout<<x[row-1]; by Xi-1 and Yj-1, plus XI or YJ get} else if (r[row][col] = = 2) lcs_print (X, Y, R, Row-1, col); Get else if (r[row][col] = = 3) lcs_print (X, Y, R, Row, col-1) by Xi-1 and YJ; 
Get else return from XI and Yj-1; //Function function: Find the maximum common substring//function parameter for two strings: X for source string 1,y for source string 2//return value: Maximum length int LCS (const char *x,const char *y) {if (x = = NUL L | | 
 
  Y = = NULL) return 0; 
  int Lenx = strlen (X); 
  int leny = strlen (Y); 
 
  if (Lenx = = 0 | | leny = 0) return 0; 
  int I, J; 
  int **c = new int *[lenx+1]; 
 
  int **r = new int *[lenx+1]; 
    Initialize for (i = 0; I <= lenx; i++) {c[i] = new int [leny+1]; 
    R[i] = new int [leny+1]; 
      for (j = 0; J <= Leny; j +) {C[i][j] = 0; 
    R[I][J] = 0; 
} 
  } 
  Start calculation for (i = 1; I <=lenX; i++) {for (j = 1; J <=lenY; J + +) {if (x[i-1] = y[j-1])//character 
        The subscript of the string starts from 0, so minus 1, i.e. X1 = x[0] Y1 = y[0] {C[i][j] = c[i-1][j-1] + 1;  R[I][J] = 1; by Xi-1 and Yj-1, plus XI or YJ get} else {if (C[i-1][j] >= c[i][j-1]) {c[i][j 
          ] = C[i-1][j];   R[I][J] = 2; 
          obtained by Xi-1 and YJ} else {c[i][j] = c[i][j-1];   R[I][J] = 3; 
  Obtained by Xi and Yj-1}}//print longest common substring lcs_print (X, Y, R, Lenx, Leny);   
  Record maximum length int LCS = C[lenx][leny]; 
    Free space for (i = 0; I <= lenx; i++) {delete [] c[i]; 
  Delete [] r[i]; 
  } Delete C; 
  Delete R; 
  R = C = NULL; 
return LCS; 
 }

      
Issue 2: Delete a specific element in the string
    specific description, enter two strings, Deletes all the characters in the second string from the first string. For example, enter "They are students." and "Aeiou", the first string after deletion becomes "Thy R stdnts."
    Ideas: This is a question of character lookup, the simplest is to examine each character of the second string, and then check that there is no this character in the first string, and some words are deleted. This time complexity is O (MN). For lookups, it is easy to think of binary lookup, hashing these concepts. The hash lookup is very fast, with a time complexity of O (1). If you can think of a hash, then it is easy to give the following solution, I believe many people can imagine. A 256-byte array is required to record the occurrence of each character in the second string, 0 for no occurrence, and 1 for the occurrence. Then iterate through the first string and query the array of records for each character to decide whether to delete it or not.
   Reference Code:

function function: Delete a specific character 
//function parameter in a string: Psrc is a source string, Pdel is a specific character set 
//return value:  empty 
void Deletespecialchars (char *psrc, char * Pdel) 
{ 
  if (psrc = null | | | pdel = NULL) return 
    ; 
  int lensrc = strlen (PSRC); 
  int Lendel = strlen (Pdel); 
  if (lensrc = = 0 | | lendel = 0) return 
    ; 
  BOOL Hash[256] = {false}; 
  for (int i = 0; i < Lendel i++)//establish the index of the deletion character 
    hash[pdel[i]] = true; 
  Start deleting 
  char *pcur = psrc; 
  while (*psrc!= ' ") 
  { 
    if (hash[*psrc] = false)//Do not delete 
      *pcur++ = *psrc; 
    psrc++; 
  } 
  *pcur = ' i '; 
}

question 3: Rotate the string to the left, but it can also be a left-spin array
To define the left rotation of a string: Move a number of characters in front of the string to the tail of the string. If the string abcdef left rotate 2 bits to get the string cdefab. Implement the function of the left rotation of the string. Requires time for a string operation of length n (n), and secondary memory is O (1).
Idea: With a little trick, if the rotated string is xy, where y is going to rotate to the front of X. Just flip the substring X and Y, and then flip the entire string again. An algorithm of STL rotate is using this.
Reference code:

function function: Flip string 
//function argument: Pbegin point to the first character, Pend point to the last character 
//return value:  empty 
void reversestring (char *pbegin, char * Pend) 
{ 
  if (Pbegin = null | | | pend = NULL) return 
    ; 
 
  while (Pbegin < pend) 
  { 
    //exchange character 
    char tmp = *pbegin; 
    *pbegin = *pend; 
    *pend = tmp; 
    Closer to the middle 
    pbegin++; 
    pend-- 
  } 
} 
 
function function: Turn string n bit 
//function parameter: PSRC as source string, n is left rotation 
//return value:  empty 
void leftrotatestring (char *psrc, unsigned n) 
{ 
  if (psrc = NULL | | n = = 0 | | | n > strlen (PSRC)) return 
    ; 
 
  int len = strlen (PSRC); 
  ReverseString (PSRC, psrc + n-1); 
  ReverseString (PSRC + N, psrc + len-1); 
  ReverseString (PSRC, psrc + len-1); 
} 


Problem 4: find the first character in a string that appears only once. If input Abaccdeff, then output B.
Idea: This problem is not difficult, because each character is only 8 bits, so you can use the counting method. First, the number of occurrences of each character in the string is counted, then the string is traversed from the beginning, and for the current character, the Query tab, if the number of occurrences is 1, prints the character.
Reference code:

function function: Finds the first occurrence of a character 
//function parameter in a string: Pstr is the source string 
//return value:  target character 
Char firstappearonce (char *pstr) 
{ 
  if (pstr = null) 
    return ' ","////not found returning null character 
 
  int count[256] = {0}; 
  char *ptmp = pstr; 
   
  while (*ptmp!= ' ")//statistics The number of occurrences of each character in the string 
  { 
    count[*ptmp]++; 
    ptmp++; 
  } 
  while (*pstr!= ' ")//traversal string, find the first occurrence of the character 
  { 
    if (count[*pstr] = 1) break 
      ; 
    pstr++; 
  } 
  return *pstr; Found characters 
} 


question 5: write a function whose prototype is int Continumax (char *outputstr,char *intputstr). Function: Find the longest string of digits in the strings, return the length of the string, and pay the longest number string to one of the function parameters outputstr the memory.
For example: After the first address of "abcd12345ed125ss123456789" is passed to Intputstr, the function returns the value of 9,outputstr is 123456789
Train of thought: This topic is relatively simple, scan a string can be, when the number of numbers plus 1, and then compared with the longest string, if the length is greater than the longest string, update the longest string; When you encounter a non-numeric number, the counter is zeroed.
Reference code: Function name and formal parameter name modified, personal habits.

function function: Find the longest consecutive number string 
//function parameter in a string: Psrc represents the source string, Pdest records the starting position//return value of the longest number string 
:  length of the longest number string 
int Continuemax (char * Psrc,char * &pdest) 
{ 
  pdest = NULL; 
  if (psrc = NULL) return 
    0; 
 
  int max = 0, cnt = 0; 
  while (*psrc!= ') 
  { 
    if (*psrc >= ' 0 ' && *psrc <= ' 9 ')/number 
    { 
      cnt++; 
      if (CNT > Max)//update the longest number string 
      { 
        pdest = psrc-cnt + 1; 
        max = cnt; 
      } 
    } 
    else 
      cnt = 0; 
    psrc++; 
  } 
  if (CNT > Max) 
  { 
    pdest = psrc-cnt + 1; 
    max = cnt; 
  } 
  return max; 
} 

Question 6:Converts a string to an integer
Problem Description: Enter a string representing an integer that converts the string to an integer and outputs it. For example, the input string "345" outputs an integer 345.
Train of thought: the process of conversion is simpler, read a character at a time, multiply the previously saved value by 10, and then add the number represented by the character. This is the normal situation. This problem is mainly to investigate the treatment of various abnormal conditions. Suppose the declaration of a function is an int strtoint (const char *STR);
(1) The input string pointer is null;
(2) The number of the front has positive and negative processing;
(3) The number represented by the string exceeds the range that the 32-bit integer can represent, that is, overflow processing;
(4) An illegal character has been entered, that is, other characters except the number and the positive sign;
(5) The string starting with the character ' 0 ' and the ' 0 ' followed by other characters are also illegal.
If these situations are handled well, the robustness of the program is greatly enhanced. Two of these situations are a bit of a hassle, first, how to handle the overflow, we can use Std::numeric_limits<int>::max (), we can define a long long variable, and then compare this to the maximum value to determine if it overflows. Second. Because the return value is an integer, what is returned if the conversion fails? If it is ' 0 ', then the normal input "0" can not be distinguished. Two scenarios, modifying the function declaration, indicating the success of the conversion by returning a value, or defining a global variable to save the success or failure of the conversion. The second scenario is used in the reference code.
Reference code: The first given is the use of Std::numeric_limits<int>::max ().

#include <iostream> #include <limits>//must include this header file using namespace std; 
    int main () {cout << "the maximum value for type float is:" << Numeric_limits<float>::max () 
  << Endl; cout << "The maximum value for type Double is:" << numeric_limits<double>::max () << en 
  dl 
  cout << "The maximum value for type int is:" << Numeric_limits<int>::max () << Endl; cout << "The maximum value for type short int is:" << numeric_limits<short Int>::max () 
;< Endl; BOOL Strtointok;  
  global variable int strtoint (const char *str) {Strtointok = false;  
    
  if (str = NULL)//null pointer return 0;  
    
  if (str[0] = = ' 0 ' && str[1]!= ' 0 ', but not "0" can actually ignore return 0;  
  unsigned i = 0;  bool minus = false; Negative sign if (str[i] = = '-' | | str[i] = = ' + ')//To determine whether to start with a positive sign {minus = (str[i] = = '-')? True:faLse  
  i++; Long long result = 0;  
    The result of the conversion while (Str[i]!= ' i ') {char c = str[i++];  
      if (c >= ' 0 ' && C <= ' 9 ') {result = result * + (C-' 0 ');  
      if (minus)//negative Overflow {if (Result-1 > Numeric_limits<int>::max ()) return 0;  
      else//Positive Overflow {if (Result > Numeric_limits<int>::max ()) return 0;  
    } else {return 0;  
  } Strtointok = true; Result returns need to force a conversion. return minus? (int)  
(-result):(int) result;  
 }

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.