刚开始还在想双指针,完全没必要。然后最土的可以扫两遍O(n),用一个数组记录出现次数。然后想到如果数组里记录出现的位置,可以只扫一遍O(n),第二遍扫字符集就行了。
#include <iostream> #include <string> using namespace std; #define INF 1<<30 int main() { string s; while (cin >> s) { int len = s.length(); if (len == 0) { cout << "-1" << endl; continue; } int count[26]; for (int i = 0; i < 26; i++) { count[i] = -1; } for (int i = 0; i < len; i++) { if (count[s[i]-'A'] == -1) { count[s[i]-'A'] = i; // save the first position } else { count[s[i]-'A'] = INF; } } int min = INF; for (int i = 0; i < 26; i++) { if (min > count[i] && count[i] != -1) min = count[i]; } if (min != INF) cout << min << endl; else cout << -1 << endl; } return 0; }