@@ -33,45 +33,23 @@ typedef long long ll;
3333
3434class UndoHistory {
3535 public:
36- string longestPrefix (string s, set<string> S){
37- string maxs;
38- for (string t : S)
39- if (isPrefix (s, t) && t.size () > maxs.size ()) maxs = t;
40- return maxs;
41- }
42- // Returns true if t is substring of s
43- bool isPrefix (string s, string t){
44- int k = t.size ();
45- return k <= s.size () && s.substr (0 , k) == t;
46- }
4736 int minPresses (vector <string> lines){
4837 string line, buffer;
49- set<string> undo;
50- int i = 0 , n = lines.size (), strokes = 1 ;
51- buffer.push_back (lines[0 ][0 ]);
52- undo.insert (buffer);
38+ int i = 0 , n = lines.size (), strokes = lines[0 ].size () + 1 ;
39+ ri (1 , n){
40+ int a = lines[i].size (), b = lines[i-1 ].size ();
41+ int mincost = a+3 ;
42+ if (a >= b && lines[i].substr (0 , b) == lines[i-1 ]) mincost = min (mincost, 1 +a-b);
5343
54- while (i < n){
55- string line = lines[i];
56- // cout<<"buffer = "<<buffer<<" strokes = "<<strokes<<endl;
57- if (buffer == line){
58- strokes++;
59- i++;
60- }
61- else {
62- string t = longestPrefix (line, undo);
63- if (isPrefix (line, buffer) && t.size () <= buffer.size ()+2 ){
64- int m = buffer.size ();
65- buffer.push_back (line[m]);
66- strokes++;
67- }
68- else {
69- buffer = t;
70- strokes += 2 ;
44+ fj (i){
45+ string l = lines[j], L = lines[i];
46+ int a = l.size (), b = L.size ();
47+ rke (1 , min (a, b)){
48+ if (L.substr (0 , k) != l.substr (0 , k)) break ;
49+ mincost = min (mincost, b-k+3 );
7150 }
72- undo.insert (buffer);
73- // cout<<"buffer = "<<buffer<<" line = "<<line<<endl;
7451 }
52+ strokes += mincost;
7553 }
7654 return strokes;
7755 }
0 commit comments