第一题: int main() { string s; cin >> s; unordered_map<char, int> m; unordered_map<char, bool> flag; int sum = 0, cur = 0; vector<int> res; for (int i = 0; i < s.size(); i++) m[s[i]]++; for (int i = 0; i < s.size(); i++) { if (flag.find(s[i]) == flag.end()) { sum += m[s[i]]; flag[s[i]] = true; } cur++; if (cur == sum) { res.push_back(cur); cur = 0; sum = 0; } } for (int i = 0; i < res.size(); i++) { if (i != res.size() - 1) cout << res[i] << ','; else cout << res[i] << endl; } system("pause"); return 0; }
#当时没有考虑n==1的情况,以及判断没有路径的情况, 只有63%
#不知道现在加上能不能ac
def dfs(res,num,fg,i,cnt):
if sum(fg) == 2 and fg[0] == 1 and num[i][0] != -1: #只剩两个城市 ,起点还未到达, 且可以返回起点
res.append(cnt+num[i][0])
return
if fg[0] == 0: #无法回到起点,起点被遍历两遍
return
for kk in range(n):
if num[i][kk] != -1 and fg[kk] > 0: #有路且去向城市未访问过
fg[i] -= 1
dfs(res,num,fg,kk,cnt+num[i][kk]) #
fg[i] += 1
return
n = int(input())
if n ==1: #考虑n==1的情况
print(0)
else:
m = int(input())
num =[[ -1 for i in range(n)] for j in range(n)]
for k in range(m): #构造邻接矩阵
i,j,d = [int(tmp) for tmp in input().split(' ')]
num[i][j] = d
num[j][i] = d
fg = [1]*n #改点是否访问标志
fg[0] = 2 #起点需访问两遍
res = []
dfs(res,num,fg,0,0)
if len(res) == 0: #考虑没有路径的情况
print(-1)
else:
print(min(res))
我后两题AC,第一题怎么都想不通过不了。 public static void main(String[] args) {
Scanner sin = new Scanner(System.in);
String schedule = sin.nextLine(); int n = schedule.length(); if(n==0)
System.out.println(0); else{
HashMap<Character,Integer> end = new HashMap<>(); for(int i=0;i<n;i++){
end.put(schedule.charAt(i),i);
} int t=0;
String res=""; while(t<schedule.length()){ int e= t; int k =e; while(k<=e){
e = Math.max(end.get(schedule.charAt(k)),e);
k++;
}
res += String.valueOf(e-t+1)+" ";
t = e+1;
}
res = res.trim();
System.out.println(res);
}
}