File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ int n;
4+ string ring,key;
5+ vector<vector<int >> memo;
6+ array<vector<int >,26 > pos;
7+
8+ int dfs (int cur,int kidx) {
9+ if (kidx==(int )key.size ()) return 0 ;
10+ int &res=memo[cur][kidx];
11+ if (res != -1 ) return res;
12+ res=INT_MAX/4 ;
13+ int ch=key[kidx]-' a' ;
14+ for (int p : pos[ch]) {
15+ int diff=abs (cur-p);
16+ int dist=min (diff,n-diff);
17+ int sub=dfs (p,kidx+1 );
18+ res=min (res,dist+1 +sub);
19+ }
20+ return res;
21+ }
22+
23+ int findRotateSteps (string ring_,string key_) {
24+ ring=ring_;
25+ key=key_;
26+ n=ring.size ();
27+ memo.assign (n,vector<int >(key.size (),-1 ));
28+ for (int i=0 ; i<26 ; ++i) pos[i].clear ();
29+ for (int i=0 ; i<n; ++i) pos[ring[i]-' a' ].push_back (i);
30+ return dfs (0 ,0 );
31+ }
32+ };
You can’t perform that action at this time.
0 commit comments