[Explanations] - [AcWing] - 778. The maximum span string

778. The maximum span string

Title Description

There are three strings S, S1, S2, wherein, S the length of not more than 300, the length S1 and S2 does not exceed 10.

Now, we want to detect whether S1 and S2 are simultaneously present in the S, S1 and S2 are located on the left, and do not cross in S (i.e., the left side of the right boundary of the left boundary point S1 of the point S2).

Calculating the maximum span satisfying the above condition (i.e., the maximum separation distance: number of characters between the start point S2 and the rightmost leftmost end point of S1).

If the condition is not satisfied in S1, S2, outputs -1.

For example, S = "abcd123ab888efghij45ef67kl", S1 = "ab", S2 = "ef", wherein, in S Sl appear twice, S2 S also appears twice, the maximum span: 18.

Input Format

Input common line, comprising three strings S, separated by commas S1, S2, string.

Three data strings to ensure no spaces and commas.

Output Format

Output An integer representing the maximum span.

If the condition is not satisfied in S1 and S2, outputs -1.

Sample input:

abcd123ab888efghij45ef67kl,ab,ef

Sample output:

18
Difficulty: hard
Time / space restrictions: 1s / 64MB
By the total number: 51
The total number of attempts: 134
Source: grammar questions
Algorithms label: String

AC Code

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int main(void)
{

    string S,S1,S2;
    int i, a, b;
    char arr[325];
    scanf("%s",&arr);
    for(i = 0; i < strlen(arr); i ++){
        if(arr[i] == ','){
            a = i;
            break;
        }
        S += arr[i];
    }//将第一个,之前的字符串输入字符串S
    for(i = a + 1; i < strlen(arr); i ++){
        if(arr[i] == ','){
            b = i;
            break;
        }
        S1 += arr[i];
    }//将两个,之间的字符串输入字符串S1
    for(i = b + 1; i < strlen(arr); i ++){
        S2 += arr[i];
    }//将第二个,之后的字符串输入字符串S2
    int s,s1,s2;
    s1=S.find(S1);
    s2=S.rfind(S2);
    if((s1+S1.length()-1)<s2){
        cout<<s2-s1-S1.length()<<endl;
    }//输出跨距
    else cout<<"-1"<<endl;
}

Thinking, summed up

The key lies in the application in C ++ string in the find and rfind

The significance of this problem in S.find (S1) is the location of the first occurrence of the string returned S S1, and this position is the position of the first character S1.

Meaning S.rfind (S2) is to return the string S S2 forward for the first time from the position, this position is the position of the first character of S2.

Published 34 original articles · won praise 2 · Views 883

Guess you like

Origin blog.csdn.net/Kapo1/article/details/104028725