数组中两个字符串的最小距离

数组中两个字符串的最小距离

题目描述

给定一个字符串数组strs,再给定两个字符串str1和str2,返回在strs中str1和str2的最小距离,如果str1或str2为null,或不在strs中,返回-1。

输入描述:

输入包含有多行,第一输入一个整数 n ( 1 ≤ n ≤ 1 0 5 ) n(1 \leq n \leq 10^5) n(1n105),代表数组strs的长度,第二行有两个字符串分别代表str1和str2,接下来n行,每行一个字符串,代表数组strs (保证题目中出现的所有字符串长度均小于等于10)。

输出描述:

输出一行,包含一个整数,代表返回的值。

示例1
输入
1
CD AB
CD
输出
-1
示例2
输入
5
QWER 666
QWER
1234
qwe
666
QWER
输出
1
备注:

时间复杂度 O ( n ) O(n) O(n),额外空间复杂度 O ( 1 ) O(1) O(1)


题解:

分别用两个下标保存 s1 和 s2 出现的位置,在遍历字符串数组时,出现其中一个,就跟另外一个字符串的位置做比较,求最小值即可。

代码:
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 11;
const int MAX = (1 << 31) - 1;

int n;
char s1[N], s2[N];
char t[N];

int main(void) {
    
    
    scanf("%d", &n);
    scanf("%s %s", s1, s2);
    if (!strcmp(s1, s2)) return 0 * puts("0");
    int end1 = -1, end2 = -1;
    int ret = MAX;
    for (int i = 0; i < n; ++i) {
    
    
        scanf("%s", t);
        if (!strcmp(s1, t)) {
    
    
            if (end2 != -1) ret = min(ret, i - end2);
            end1 = i;
        }
        if (!strcmp(s2, t)) {
    
    
            if (end1 != -1) ret = min(ret, i - end1);
            end2 = i;
        }
    }
    if (ret == MAX) ret = -1;
    printf("%d\n", ret);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/MIC10086/article/details/108863994
今日推荐