A summary of string questions of sword finger offer

Keywords: Programming less

The types of questions about strings in question library are as follows

  • String, character array, integer conversion, etc
  • Rule judgement

  • Digital operation

  • Related to Array Operations

  • dynamic programming

  • Advanced data structure

1. Conversion of string, character array, integer, etc

(1) Conversion between string and character array

int main()
    string s = "hello";
    const char* s1 = NULL;
    //string to const char*
    s1 = s.c_str();

    char* s2 = NULL;
    const char* s3 = NULL;
    /*string Turn char*
     * Convert string to const char first*
     * Convert const char to char
    s3 = s.c_str();
    s2 = const_cast<char*>(s3);
    //string to char [], assign by subscript
    char s4[10] = {0};
    for(int i = 0; i < s.length(); i++){
        s4[i] = s[i];
    //const char * to string
    const char* s5 = "hello";
    string s6;
    s6 = s5;
    char* s7 = NULL;
    //char [] can be directly assigned to other types

Note the difference between const char *, char *, char [] here. For char *, it points to a piece of memory where the string is stored. It is not allowed to change its pointing content, but it can change its pointing object. Char [] is readable and writable. The main thing to note is that the lower string can only be converted to const char *.

(2) String and integer

Here are two functions to remember

String to integer

int atoi(const char *str );

Integer to string

sprintf(str, "%d", rand());

2. Rule judgment

(1) Conform to integer rule

Look at a question on the sword finger: convert a string to an integer

int StrToInt(string str) {
        const int length = str.length();
        int isNegtive = 1, overValue = 0;
        int digit = 0, value = 0;
        if (length == 0) return 0;
        else {
            int idx = 0;
            if (str[0] == '-') { isNegtive = -1; idx = 1;}
            else if (str[0] == '+') {idx = 1;}
            for (; idx<length; idx++) {
                digit = str[idx]-'0';
                // overValue indicates whether the current cycle will cross the boundary
                overValue = isNegtive*value - INT_MAX/10
                          + (((isNegtive+1)/2 + digit > 8) ? 1:0);
                if (digit<0 || digit>9) return 0;
                else if (overValue > 0) return 0;
                value = value*10 + isNegtive*digit;
            return value;

Pay attention to the over boundary judgment of integers. Before each round of cyclic addition, judge whether the next addition will overflow or not

 overValue = isNegtive*value - INT_MAX/10+ (((isNegtive+1)/2 + digit > 8) ? 1:0);

(2) Compliance with floating point rules

Implement a function to determine whether a string represents a number, including integers and decimals. For example, the strings "+ 100","5e2","-123","3.1416" and "- 1E-16" all represent numeric values. But "12e","1a3.14","1.2.3","+-5" and "12e+4.3" are not.

bool isNumeric(char* string)
        bool sig = false;
        bool ife = false;
        bool dec = false;
        for(int i=0;i<strlen(string) ;i++){
                 if (string[i] == 'e' || string[i] == 'E') {
                if (i == strlen(string)-1) return false; // e. be sure to put numbers in the back
                if (ife) return false;  // Two e's cannot exist at the same time
                ife = true;
            } else if (string[i] == '+' || string[i] == '-') {
                // The second occurrence of the + - sign must be immediately after e
                if (sig && string[i-1] != 'e' && string[i-1] != 'E') return false;
                // The first occurrence of the + - sign, which is not at the beginning of a string, must also follow e
                if (!sig && i > 0 && string[i-1] != 'e' && string[i-1] != 'E') return false;
                sig = true;
            } else if (string[i] == '.') {
              // e can not be followed by decimal point, decimal point can not appear twice
                if (ife || dec) return false;
                dec = true;
            } else if (string[i] < '0' || string[i] > '9') // Illegal character
                return false;
        return true;

3. Number operation

There is a large integer addition, subtraction, multiplication and division, and the same string is converted to an integer, mainly to pay attention to overflow judgment

4. Related to the operation in the following table

Character adjustment, sorting, replacement, etc

(1) Please implement a function to replace each space in a string with "% 20". For example, when the string is We Are Happy, the replaced string is We%20Are%20Happy.

void replaceSpace(char *str,int length) {
            //Traverse one side string to find the number of spaces
            return ;
        int i=0;
        int oldlen=0;//Record previous length
        int space=0;//Number of record spaces
               if(str[i]==' ')
        int newlen=oldlen+space*2;//Length after insertion
        if(newlen>length)//If the calculated length is greater than the total length, it cannot be inserted
            return ;
        while(oldlen>=0 && newlen>oldlen)//Character playing
              if(str[oldlen]==' ') //Replace when space is encountered
               else //Not spaces

The idea is to first calculate the number of spaces, so as to calculate the total length of the string after replacement, and then add from the back to the front, so that each character moves less.

(2) Enter a string and print all the permutations of the characters in the string in dictionary order

void swap(char& p,char& q){
    char temp = p;
    p = q;
    q = temp;

void perm(string& str,vector<string>& res, int begin)
    if(begin == str.length()-1){
        if(find(res.begin(),res.end(),str) == res.end()){
        return ;
        for(int i=begin;i<str.length();i++){

int main()
    string s = "abcd";
    vector<string> res;
    int begin = 0;
    for(int i=0;i<res.size();i++){
    return 0;

The idea is recursion. Fix the first character, recursively obtain all kinds of string combinations after the first character; then exchange the first character with each of the following characters, and recursively obtain the string combinations after the first character; the exit of recursion is when there is only one character left, the recursion cycle is to exchange with the first character from the second character of each substring in turn, and then continue Continue processing substring

(3) Find all combinations of characters

void perm(char* str,vector<char>& res, int begin)
    if(begin == 0){
        for(int i=0;i<res.size();i++){
        return ;
    if(*str == '\0')
        return ;


int main()
    char s[] = "abcd";
    vector<char> res;
    for(int i = 1;i <= strlen(s);i++){
    return 0;

For the combination of n-length string, if its length is n, set the loop from 1 to n. Find the combination whose length is m. for the first character, it can be added in, and then m-1 characters will be needed later. It can not be added in, and then M characters will be selected later.

(4) Move the string loop n bits to the left

string LeftRotateString(string str, int n) {
         reverse(str.begin(), str.end());
        reverse(str.begin(), str.begin() + str.size() - n);
        reverse(str.begin() + str.size() - n, str.end());
        return str;

6. Dynamic planning

Find the longest common substring, the longest common substring, the longest palindrome substring, the longest palindrome substring, etc. (write another summary)

7. Advanced algorithm


32 original articles published, 13 praised, 3688 visited
Private letter follow

Posted by Hiro on Sat, 01 Feb 2020 06:04:09 -0800