Lesson 5 string

1. Basic knowledge

1. Characters and integers can be converted to each other, for example

#include <iostream>
using namespace std;

int main()
{
 	char a1[] = {'C', '+', '+'};
	cout <<"a1:" << a1 << " size:" << sizeof(a1) << endl;
	char a2[] = {'C', '+', '+', '\0'};
	cout <<"a2:" << a2 << " size:" << sizeof(a2) << endl;
	//report errors
	//char a3[3] = {'C', '+', '+', '\0'};
	//cout << "a3:" << a3 << " size:" << sizeof(a3) << endl;
	char a4[6] = {'C', '+', '+', '\0'};
	cout << "a4:" << a4 << " size:" << sizeof(a4) << endl;
   return 0;
}

2. The string is the character array plus' \ 0 '
3. Zero in C + + is particularly flexible. It is 0 in int, '\ 0' in string, null pointer and false in bool. They are equivalent to each other.
4. Input and output of string

#include <iostream>
using namespace std;
int main()
{
	char a[100];
	//End the input when a space is encountered
	scranf("%s", a);
	cout << a << endl;
	//Put automatic line feed
	puts(a);
	return 0;
}

5. The data type is char array
The simplest way to write

#include <iostream>
using namespace std;
int main()
{
	char s[10];
	cin >> s;
	return 0;
} 

String array input gets is not safe. The advantage of using fgets() is that it is safe and spaces are input Fgets () does not filter carriage returns automatically.

#include <iostream>
using namespace std;

int main()
{
	char a[100];
	//The first parameter is the storage address, the second parameter is the maximum storage unit, and the third parameter is where to get the string
	//stdin is a system variable that reads the standard into a file and accepts input from the keyboard
	fgets(a, 100, stdin);
	cout << a  << endl;
	return 0;
}
#include <iostream>
using namespace std;

int main()
{
   char s[100];
	cin.getline(s, 100);
	cout << s << endl;
   return 0;
}

6. The data type is string.
getline input data to string type

#include <iostream>
using namespace std;

int main()
{
	string s;
    getline(cin, s);
	cout << s  << endl;
	return 0;
}

7. Common string functions
Header file string h. You can find that this is a c file

strlen()
//A < B, return - 1;a == b, return 0; A > b, return to 1. The way of comparison here is the dictionary sequence, which is related to greed
strcmp(a, b)
//Copy string b to string a
strcpy(a, b)

8. The input string has no spaces. Use cin and scanf; If there are spaces, use fgets, getline, and cin getlines
9. The string library string cannot be read in with scanf. Printf ('% s \ n', S1. C_str()) can be output with printf
10. Input string getline(cin, s) and cin Getline (s, 100) can also be used when available; cin can only read the string before the first space
11. Check whether the string is empty S1 Empty(), returns 1 if it is empty, and 0 if there is something; s1.size() returns the length of the string, and the time complexity is O(1). There is a variable in it to store the length of the string, while strlen's time complexity is O(n);
12. The objects of the string class support addition and ratio size
13. There is a special way to write the object for loop of string class

#include <iostream>
using namespace std;
int main()
{
	string s = "hello world!";
	for(char c: s) cout << c << endl;
	return 0;
}
#include <iostream>
using namespace std;
int main()
{
	string s = "hello world!";
	for(char c: s)
	{
		c = '+';
	}
	puts(s.c_str());//The output string has not changed
	return 0;
}
#include <iostream>
using namespace std;
int main()
{
	string s = "hello world";
	for(auto &c: s)//auto can guess the data type
	{
		c = '+';
	}
	puts(s.c_str());
	return 0;
}

2. Exercises

2.1 string length

Given a non empty string with a length of no more than 100, please find its specific length.

Input format
Enter a line representing a string. Note that the string may contain spaces.

Output format
Outputs an integer representing its length.

Input example:
I love Beijing.
Output example:
15

#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
    string s;
    getline(cin, s);
    
    int len = 0;
    for(auto c : s) len ++;
    
    cout << len << endl;
    return 0;
}

2.2 number of digits in string

Enter a line of characters with a length of no more than 100. Please count the number of numeric characters.

Input format
Enter a line of characters. Note that it may contain spaces.

Output format
Output an integer representing the number of numeric characters.

Input example:
I am 18 years old this year.
Output example:
2

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s;
    getline(cin, s);
    
    int len = 0;
    for(auto c: s)
    {
        if(c >= '0' && c <= '9') len ++;
    }
    
    cout << len << endl;
    return 0;
}

2.3 cyclic phase restriction

Circular phase kering is a small game played by two people.

The order word is "hunter, bear and gun". They say the order word at the same time and make an action at the same time - the action of the hunter is to put their hands on their hips; The action of a bear is to put his hands on his chest; The action of the gun is to raise both hands in the shape of a pistol.

The two sides decide whether to win or lose by this action. If the hunter wins the gun, the gun wins the bear, and the bear wins the hunter, if the action is the same, it will be regarded as a draw.

Now, given a series of action combinations, please judge the result of the game.

Input format
The first row contains the integer T, indicating that there are t groups of test data.

Next, line T, each line contains two strings representing the actions made by two people in a game. The string is one of hunter, bear and gun. These three words represent hunter, bear and gun respectively.

Output format
If the first player wins, Player1 is output.

If the second player wins, Player2 is output.

If there is a draw, Tie is output.

Data range
1≤N≤100
sample input
3
Hunter Gun
Bear Bear
Hunter Bear
sample output
Player1
Tie
Player2

2.3. 1 Analysis

This question is very meaningful. When two people play games, there are three kinds of words for one person, that is, there are nine cases in total. Non optimized programming requires writing 9 if rules. The optimized algorithm encodes the word order.

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1, s2;
    int c1, c2;
    int n;
    cin >> n;
    
    while(n --)
    {
        cin >> s1 >> s2;
        
        if(s1 == "Hunter") c1 = 0;
        else if(s1 == "Bear") c1 = 1;
        else if(s1 == "Gun") c1 = 2;
        
        if(s2 == "Hunter") c2 = 0;
        else if(s2 == "Bear") c2 = 1;
        else if(s2 == "Gun") c2 = 2;
        
        
        if(c1 == c2) puts("Tie");
        else if(c1 == (c2 + 1) % 3) puts("Player1");
        else puts("Player2");
        
    }
    return 0;
}

2.4 string plus space

Given a string, add a space between each character of the string.

Output the modified new string.

Input format
A line containing a string. Note that the string may contain spaces.

Output format
Output the string after adding spaces.

Data range
1 ≤ string length ≤ 100
Input example:
test case
Output example:
t e s t c a s e

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s1, s2;
    getline(cin, s1);
    
    for(auto c: s1)
    {
        s2 = s2 + c + ' ';
    }
    //s2.pop_back();// Delete the last character
    puts(s2.c_str());
    return 0;
}

2.5 replacement characters

Give a string of uppercase and lowercase letters.

Replace all specific characters in the string with characters # instead.

Please output the replaced string.

Input format
There are two lines to enter.

The first line contains a string no longer than 30.

The second line contains a character that represents the specific character to replace.

Output format
Output a total of one line, which is the replaced string.

Input example:
hello
l
Output example:
he##o

#include <iostream>
using namespace std;

int main()
{
    char a[31];
    cin >> a;
    char c;
    cin >> c;
    
    for(int i = 0; a[i] != '\0'; i ++)
    {
        if(a[i] == c) a[i] = '#';
    }
    
    puts(a);
    return 0;
}

2.6 string insertion

There are two strings STR and substr that do not contain white space characters. The number of characters in str is no more than 10 and the number of characters in substr is 3. (the number of characters does not include \ 0 at the end of the string.)

Insert substr after the character with the largest ASCII code in str. if there are multiple maxima, only the first one will be considered.

Input format
The input includes several lines, each line has a set of test data, and the format is

str substr

Output format
For each set of test data, the inserted string is output.

Input example:
abcab eee
12343 555
Output example:
abceeeab
12345553

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1, s2;
    while(cin >> s1 >> s2)
    {
        int max_tmp = -9999;
        int flag = 0;
        for(int i = 0; s1[i]; i ++)
        {
            if(s1[i] > max_tmp) max_tmp = s1[i], flag = i;
        }
    	//C + + character splicing function substr()
        cout << s1.substr(0, flag + 1) + s2 + s1.substr(flag + 1) << endl;    
    }
    return 0;
}

2.7 characters that appear only once

Give you a string that contains only lowercase letters.

Please judge whether there are characters that appear only once in the string.

If it exists, the character with the highest position in the qualified character is output.

If not, output no.

Input format
A line containing a string of lowercase letters.

The data guarantees that the length of the string does not exceed 100000.

Output format
Output the first character that meets the condition.

If not, no is output.

Input example:
abceabcd
Output example:
e

#include <iostream>
#include <cstdio>
using namespace std;
//Large arrays are placed outside the main function to open up memory in the heap. The stack space of the main program is not very large.
char s[100010];
int main()
{
	//How many times did the status array tag character appear
    int a[27] = {0};
    
    
    scanf("%s", s);
    
    int tmp = 0;
    for(int i = 0; s[i] != '\0'; i ++)
    {
        tmp = s[i] - 'a';
        a[tmp] ++;
    }
    
    // for(int i = 0; i < 26; i ++) cout << a[i] << endl;
    
    for(int i = 0; s[i] != '\0'; i ++)
    {
        int flag = s[i] - 'a';
        if(a[flag] == 1) 
        {
            printf("%c", s[i]);
           	return 0;
        }
    }
    puts("no"); 
    
    return 0;
}

2.8 string matching

Give two strings a and b of the same length.

If the character a[i] on string a is the same as the character b[i] on string b at a certain position I, the character at this position is matched.

If the ratio of the number of matching positions of two strings to the total length of the strings is greater than or equal to k, the two strings are said to match.

Now please judge whether the given two strings match.

Input format
The first line contains a floating-point number k, the second line contains string a, and the third line contains string b.

The string you entered does not contain spaces.

Output format
If the two strings match, yes is output.

Otherwise, no is output.

Data range
0≤k≤1,
The length of the string does not exceed 100.

Input example:
0.4
abcde
xbacd
Output example:
no

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1, s2;
    double k;
    cin >> k >> s1 >> s2;
    
    double tmp = 0;
    for(int i = 0; i < s1.size(); i ++)
    {
        if(s1[i] == s2[i]) tmp ++;
    }
    
    if(tmp / s1.size() >= k) cout << "yes" << endl;
    else cout << "no" << endl;
    return 0;
}

2.9 ignoring case and comparing string sizes

Generally, we can use strcmp to compare the size of two strings. The comparison method is to compare the two strings from front to back character by character (according to the size of ASCII code value) until different characters appear or \ 0 is encountered.

If all characters are the same, they are considered the same; If different characters appear, the comparison result of the first different character shall prevail.

But sometimes, when we compare the size of strings, we want to ignore the size of letters. For example, hello and hello are equal when ignoring the case of letters.

Please write a program to compare the case of two strings ignoring the case of letters.

Input format
The input is two lines, one string per line, a total of two strings. Note that the string may contain spaces.

The data guarantees that the length of each string does not exceed 80.

Output format
If the first string is smaller than the second string, output a character <.

If the first string is larger than the second string, output a character >.

If two strings are equal, output a character =.

Input example:

Hello
hello

Output example:

=

#include <cstdio>
#include <cstring>

using namespace std;
int main()
{
    //I wanted to use the string class, but strcmp does not support it
    char s1[100], s2[100];
    //cin does not support space input
    fgets(s1, 100, stdin);
    fgets(s2, 100, stdin);
    
    //Remove the newline space. fgets cannot automatically filter the newline character. Note that the newline character is in the last second position
    if(s1[strlen(s1) - 1] == '\n') s1[strlen(s1) - 1] = 0;
    if(s2[strlen(s2) - 1] == '\n') s2[strlen(s2) - 1] = 0;
    
    
    for(int i = 0; s1[i]; i ++)
    {
        if(s1[i] >= 'A' && s1[i] <= 'Z') s1[i] += 32;
    }
    
    for(int i = 0; s2[i]; i ++)
    {
        if(s2[i] >= 'A' && s2[i] <= 'Z') s2[i] += 32;
    }
    // puts(s1);
    int tmp = strcmp(s1, s2);
    if(tmp == 0) puts("=");
    else if(tmp > 0) puts(">");
    else if(tmp < 0) puts("<");
    
    return 0;
}

2.10 remove redundant spaces

Enter a string, which may contain multiple consecutive spaces. Please remove the extra spaces and leave only one space.

Input format
A line containing a string.

Output format
Output the string after removing redundant spaces, accounting for one line.

Data range
The length of the input string does not exceed 200.
Ensure that there are no spaces at the beginning and end of the input string.

Input example:
Hello world.This is c language.
Output example:
Hello world.This is c language.

//This method uses the method of double pointer marking
#include <iostream>
#include <string>
using namespace std;

int main()
{
    char s1[201], s2[201];
    fgets(s1, 201, stdin);
    
    for(int i = 0, j = 0; s1[i] != '\0';)
    {
        if(s1[i] != ' ')
        {
            s2[j] = s1[i];
            j ++;
            i ++;
        }
        else if(s1[i] == ' ')
        {
            s2[j] = s1[i];
            while(s1[i] == ' ') i ++;
            j ++;
        }
        //Fill in the last digit with the ending digit
        if(s1[i] == '\0') s2[j] = '\0';
    }
    cout << s2;
    
    return 0;
}
//Method 2
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s;
    while(cin >> s) cout << s << " ";
    return 0;
}

2.11 information encryption

In the process of transmitting information, in order to ensure the security of information, we need to encrypt the original information to form encrypted information, so that the information content will not be stolen by the listener.

Now give a string and encrypt it.

The encryption rules are as follows:

The lowercase letter in the string, a is encrypted as b, b is encrypted as c,..., y is encrypted as z, and z is encrypted as a.
The uppercase letter in the string. A is encrypted as B, B is encrypted as C,..., Y is encrypted as Z, and Z is encrypted as a.
Other characters in the string are not processed.
Please output the encrypted string.

Input format
A line containing a string. Note that the string may contain spaces.

Output format
Output encrypted string.

Data range
The length of the input string does not exceed 100.

Input example:
Hello! How are you!
Output example:
Ifmmp! Ipx bsf zpv!

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s;
    getline(cin, s);
    
    char tmp;
    for(int i = 0; s[i] != '\0'; i ++)
    {
        if(s[i] >= 'a' && s[i] <= 'y') s[i] += 1;
        else if(s[i] == 'z') s[i] = 'a';
        else if(s[i] >= 'A' && s[i] <= 'Y') s[i] += 1;
        else if(s[i] == 'Z') s[i] = 'A';
    }
    puts(s.c_str());
    return 0;
}

Improved writing

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s;
    getline(cin, s);
    
    char tmp;
    for(auto &c: s)
    {
        if(c >= 'a' && c <= 'z') c = 'a' + (c - 'a' + 1) % 26;
        if(c >= 'A' && c <= 'Z') c = 'A' + (c - 'A' + 1) % 26;
    }
    puts(s.c_str());
    return 0;
}

2.12 output string

Given a string a, please output string b according to the following requirements.

Given the ASCII value of the first character of string a plus the ASCII value of the second character, the first character of b is obtained;

Given the ASCII value of the second character of string a plus the ASCII value of the third character, the second character of b is obtained;

...

Given the ASCII value of the penultimate character of string a plus the ASCII value of the last character, the penultimate character of b is obtained;

Given the ASCII value of the last character of string a plus the ASCII value of the first character, the last character of b is obtained.

Input format
Enter a line containing the string a. Note that the string may contain spaces.

The data guarantees that the ASCII value of characters in the string does not exceed 63.

Output format
The output is a line containing the string b.

Data range
Length of 2 ≤ a ≤ 100
Input example:
1 2 3
Output example:
QRRSd

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1, s2;
    getline(cin, s1);
    int len = s1.size();
    
    for(int i = 0; s1[i] != '\0'; i ++)
    {
        //Traditional writing
        // if(i + 1 <= len - 1) 
        // {
        //     s2 = s2 + (char)(s1[i] + s1[i + 1]);
        // }
        // else s2 += (s1[i] + s1[0]);
        
        //Using mathematical formulas
        s2 += (s1[i] + s1[(i + 1) % len]);
    }
    cout << s2 << endl;
    return 0;
}

2.13 word replacement

Enter a string that ends with a carriage return (the string length does not exceed 100).

The string consists of several words separated by a space. All words are case sensitive.

Now you need to replace one word with another and output the replaced string.

Input format
Enter a total of 3 lines.

The first line is a string containing multiple words s;

The second line is the word a to be replaced (no longer than 100);

Line 3 is the word B (no longer than 100) where a will be replaced.

Output format
A total of one line, output the string after replacing all words a in s with b.

Input example:
You want someone to help you
You
I
Output example:
I want someone to help you

//This is done with string stream. The advantage of converting a string into string stream is that spaces will become the parameters of the internal boundary of string parameters
//KMP algorithm can also be used
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    string s1, s2, s3;
    getline(cin, s1);
    cin >> s2 >> s3;
    
    stringstream ssin(s1);
    string tmp;
    while(ssin >> tmp)
    {
        if(tmp == s2) cout << s3 << " ";
        else cout << tmp << " ";
    }
    
    return 0;
}
//stringstream uses the sample, which is equivalent to cin
//cin way
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    string s1;
    getline(cin, s1);
    
    stringstream ssin(s1);
    
    int a, b;
    string c;
    double d;
    
    ssin >> a >> b >> c >> d;
    
    cout << a << endl << b << endl << c << endl << d;
    
    return 0;
}
//Method of sscanf()
#include <cstdio>
#include <iostream>
using namespace std;

int main()
{
    char s[100];
    fgets(s, 100, stdin);
    
    int a, b;
    char str[100];
    double c;
    
    sscanf(s, "%d%s%d%lf", &a, str, &b, &c);
    
    printf("%d\n%s\n%d\n%lf", a, str, b, c);
    
    return 0;
}

2.14 the longest consecutive character in a string

Find the longest consecutive character in a string and output the character and its occurrence times. There are no white space characters (space, carriage return and tab) in the string. If there is more than one such character, the first one will be output.

Input format
In the first line, enter the integer N, which represents the number of groups of test data.

Each group of data occupies one line and contains a string without white space characters. The length of the string shall not exceed 200.

Output format
A total of one line, output the longest consecutive characters and their occurrence times, separated by spaces.

Input example:
2
aaaaabbbbbcccccccdddddddddd
abcdefghigk
Output example:
d 10
a 1

//Double pointer algorithm I
//Pointer i traverses the string, and pointer j records the first coordinate in consecutive characters
#include <iostream>
using namespace std;

int main()
{
    int n; 
    cin >> n;
    
    while(n --)
    {
        string str;
        cin >> str;
        
        int len = 1;
        int max_len = 0;
        int flag = 0;
        for(int i = 0, j = 0; str[i]; i ++)
        {
            if(str[i + 1] == str[i])
            {
                len ++;
                continue;
            }
            else
            {
                if(len > max_len) 
                {
                    max_len = len;
                    len = 1;
                    // cout << "max_len:"<< max_len << endl;
                    // cout << "zuobiao:"<< j << endl;
                    flag = j;
                    j = i + 1;
                }
                else
                {
                    len = 1;
                    j = i + 1;    
                }
                
            }
        }
        
        cout << str[flag] << " " << max_len << endl;
        
    }
    
    return 0;
}
//Simpler double pointer algorithm
//The i pointer is the first coordinate of the continuous string, and the j pointer traverses from the first coordinate of the continuous string to the last coordinate of the continuous string
#include <iostream>
using namespace std;

int main()
{
    int n; 
    cin >> n;
    
    while(n --)
    {
        string str;
        cin >> str;
        
        int max_len = 0;
        char tmp;
        for(int i = 0; i < str.size(); i ++)
        {
            int j = i;
            while(j <= str.size() && str[j] == str[i]) j ++;
            if(j - i > max_len) max_len = j - i, tmp = str[i];
            i = j - 1;
        }
        
        cout << tmp << " " << max_len << endl;
    }
    
    return 0;
}

2.15 longest word

One by one A simple English sentence at the end. The words are separated by spaces. There are no abbreviations and other special forms. Find the longest word in the sentence.

Input format
Enter this simple English sentence with a length of no more than 500.

Output format
The longest word in the sentence. If more than one, the first one is output.

Input example:
I am a student of Peking University.
Output example:
University

#include <iostream>
using namespace std;

int main()
{
    string str, res;
    
    while(cin >> str)
    {
        if(str.back() == '.') str.pop_back();
        if(str.size() > res.size()) res = str;
    }
    
    cout << res << endl;
    return 0;
}

2.16 inverted words

Write a program, read in a line of English (only letters and spaces, separated by a single space between words), reverse the order of all words and output, still separated by a single space.

Input format
Input as a string (string length up to 100).

Output format
The output is a string sorted as required.

Input example:
I am a student
Output example:
student a am I

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s[100];
    
    int i = 0;
    while(cin>> s[i]) i ++;
    
    for(int j = i - 1; j >= 0; j --)
    {
        cout << s[j] << " ";
    }
    return 0;
}

2.17 string shift inclusion problem

For a string, define a cyclic shift operation as: move the first character of the string to the end to form a new string.

Given two strings s1 and s2, it is required to determine whether one string is a substring of a new string after the other string is shifted several times.

For example, CDAA is a substring of BCDAA, a new string generated after two shifts of AABCD, while ABCD and ACBD cannot obtain a substring of the new string through multiple shifts.

Input format
A line containing two strings separated by a single space.

The string contains only letters and numbers and is no longer than 30.

Output format
If a string is a substring of a new string generated by several cyclic shifts of another string, true is output; otherwise, false is output.

Input example:
AABCD CDAA
Output example:
true

//This is a violent practice. The idea is simple, shift first, and then
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    string s1, s2;
    cin >> s1 >> s2;
    if(s1.size() < s2.size()) swap(s1, s2);
    
    string tmp1, tmp2;
    for(int i = 0; i < s1.size(); i ++)
    {
        tmp1 = s1.substr(i, s1.size() - i) + s1.substr(0, i);
        //Check if s2 is a subset of s1
        for(int k = 0; k < tmp1.size(); k ++)
        {
            for(int j = k + 1; j < tmp1.size(); j ++)
            {
                tmp2 = tmp1.substr(k, j - k + 1);
                if(tmp2 == s2)
                {
                    cout << "true" << endl;
                    return 0;
                }
                else continue;
            }
        }
    }
    cout << "false" << endl;
    return 0;
}

2.18 string power

Given two strings a and b, we define a × b is their connection.

For example, if a=abc and b=def, then a × b=abcdef.

If we consider the connection as multiplication, the power of a nonnegative integer will be defined in the usual way: a0 = ` ` (empty string), a(n+1)=a × (an).

Input format
The input contains multiple groups of test samples, each of which occupies one line.

Each set of samples contains a string s, whose length does not exceed 100.

The final test sample will be followed by a dot as a line.

Output format
For each s, you need to output the maximum n so that there is a string a, let s=an.

Input example:
abcd
aaaa
ababab
.
Output example:
1
4
3

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str;
    
    while(cin >> str, str != ".")
    {
        int len = str.size();
        //Here's a trick. From the maximum decrement, the N required by the first symbol is the maximum n
        for(int n = len; n; n--)
        {
            if(len % n == 0) 
            {
                int m = len / n;
                string res;
                string par = str.substr(0, m);
                for(int j = 0; j < n; j ++)
                {
                    res += par;
                }
                if(res == str)
                {
                    cout << n << endl;
                    break;
                }
            }
        }
        
    }
    return 0;
}

2.19 maximum span of string

There are three strings S, S1 and S2, where the length of s does not exceed 300 and the length of S1 and S2 does not exceed 10.

Now, we want to detect whether S1 and S2 appear in s at the same time, and S1 is located on the left of S2 and does not cross each other in S (that is, the right boundary point of S1 is on the left of the left boundary point of S2).

Calculate the maximum span that meets the above conditions (i.e., the maximum spacing: the number of characters between the starting point of the rightmost S2 and the ending point of the leftmost S1).

If there is no S1 and S2 that meet the conditions, output − 1.

For example, S= abcd123ab888efghij45ef67kl, S1= ab, S2= ef, where S1 occurs twice in s, S2 also occurs twice in s, and the maximum span is 18.

Input format
Enter a line containing three strings S, S1 and S2 separated by commas.

The data guarantees that the three strings do not contain spaces and commas.

Output format
Outputs an integer representing the maximum span.

If no S1 and S2 that meet the conditions exist, output − 1.

Input example:
abcd123ab888efghij45ef67kl,ab,ef
Output example:
18

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s, s1, s2;
    char c;
    while(cin >> c, c != ',') s += c;
    while(cin >> c, c != ',') s1 += c;
    while(cin >> c) s2 += c;
    
    //l is the left cursor of string s
    int l = 0;
    bool flag1 = false;
    while(l + s1.size() <= s.size())
    {
    	//i is the cursor of string s1
        for(int i = 0; i < s1.size(); i ++)
        {
            if(s1[i] != s[l + i])
            {
                if(l + i + 1 == s.size())
                {
                    puts("-1");
                    return 0;
                }
                else break;
            }
            else
            {
                if(i + 1 == s1.size())
                {
                    flag1 = true;
                    break;      
                }
                continue;
            }
        }
        if(flag1) break;
        l ++;
    }

	//r is the right cursor of string s
    int r = s.size() - s2.size();
    bool flag2 = false;
    while(r >= 0)
    {
    	//i is the cursor on string s2
        for(int i = 0; i < s2.size(); i ++)
        {
            if(s2[i] != s[r + i])
            {
                if(r + i  + 1 == s2.size())
                {
                    puts("-1");
                    return 0;
                }
                else break;
            }
            else
            {
                if(i + 1 == s2.size())
                {
                    flag2 = true;
                    break;
                }
                continue;
            }
        }
        if(flag2) break;
        r --;
    }
    
    if(r <= l)
    {
        puts("-1");
        return 0;
    }
    
    cout << r - (l + s1.size()) << endl;
    return 0;
}

2.20 longest common string suffix

Give several strings and output the longest common suffix of these strings.

Input format
It consists of several sets of inputs.

The first line of each set of inputs is an integer N.

When N is 0, the input ends, otherwise there will be N lines of input, and each line is a string (the string does not contain blank characters).

The length of each string shall not exceed 200.

Output format
A total of one line, the longest common suffix of N strings (may be empty).

Data range
1≤N≤200
Input example:
3
baba
aba
cba
2
aa
cc
2
aa
a
0
Output example:
ba

a

#include <iostream>
#include <string>
using namespace std;

const int N = 200;
string s[N];

int main()
{
    int n;
    string s[N];
    
    
    while(cin >> n, n)
    {
        int min_len = 1000;
        for(int i = 0; i < n; i ++)
        {
            cin >> s[i];
            if(min_len > s[i].size()) min_len = s[i].size();
        }
        
        
        while(min_len)
        {
            bool is_success = true;
            for(int i = 1; i < n; i ++)
            {
                bool is_same = true;
                for(int j = 1; j <= min_len; j ++)
                {
                    if(s[0][s[0].size() - j] != s[i][s[i].size() - j])
                    {
                        is_same = false;
                        break;
                    }
                }
                if(!is_same)
                {
                    is_success = false;
                    break;
                }
            }
            if(is_success) break;
            min_len --;
        }
        
         cout << s[0].substr(s[0].size() - min_len) << endl;
    }
   
    return 0;
}

Keywords: C C++ Algorithm greedy algorithm

Added by XenoPhage on Fri, 24 Dec 2021 22:57:18 +0200