題目描述:
計算兩個字符串str1和str2在給定的含有n個元素的字符串數組strs中出現的最短距離。
詳細解釋:
- 定義整數變量n,用于存儲字符串數組strs的長度。
- 定義一個vector<string>類型的變量strs,用于存儲輸入的字符串。
- 定義兩個字符串變量str1和str2,用于存儲輸入的兩個字符串。
- 使用循環,從輸入中讀取字符串str1和str2,并將它們存儲在str1和str2中。
- 使用循環,從輸入中讀取n個字符串,并將它們存儲在strs中。
- 定義兩個整數變量count1和count2,用于存儲字符串str1和str2在strs中出現的下標。
- 定義一個整數變量ret,用于存儲最短距離。
- 使用循環,遍歷字符串數組strs。
- 如果當前字符串等于str1,則將count1設置為當前下標i。
- 如果當前字符串等于str2,則將count2設置為當前下標i。
- 如果count1和count2都不等于-1,則計算它們之間的距離,并將其與當前的ret進行比較。
- 如果ret等于n,則輸出-1,表示沒有找到最短距離。
- 否則,輸出ret,表示最短距離。
具體代碼:
int main() {int n;cin >> n;vector<string> 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;elsestd::cout << ret;return 0;
}
?結果: