计算两个字符串str1和str2在给定的含有n个元素的字符串数组strs中出现的最短距离。
具体代码:
int main() { int n; cin >> n; vector strs; string str1, str2; cin >> str1 >> str2; for (int i = 0; i < n; i++) { string str; cin >> str; strs.push_back(str); } int count1 = -1, count2 = -1; int ret = n; for (int i = 0; i < n; i++) { if (strs[i] == str1 ) { count1 = i; } if (strs[i] == str2 ) { count2 = i; } if (count1 != -1 && count2 != -1 ) { int count = abs(count1 - count2); ret = min(ret,count); } } if (ret == n) std::cout << -1; else std::cout << ret; return 0; }
结果: