You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/3000-3099/3014.Minimum Number of Pushes to Type Word I/README_EN.md
+62-4Lines changed: 62 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -61,24 +61,82 @@ It can be shown that no other mapping can provide a lower cost.
61
61
62
62
## Solutions
63
63
64
-
### Solution 1
64
+
### Solution 1: Greedy Algorithm
65
+
66
+
We notice that all the letters in the string $word$ are different. Therefore, we can greedily distribute the letters evenly across the $8$ keys to minimize the number of key presses.
67
+
68
+
The time complexity is $O(n / 8)$, where $n$ is the length of the string $word$. The space complexity is $O(1)$.
65
69
66
70
<!-- tabs:start -->
67
71
68
72
```python
69
-
73
+
classSolution:
74
+
defminimumPushes(self, word: str) -> int:
75
+
n =len(word)
76
+
ans, k =0, 1
77
+
for _ inrange(n //8):
78
+
ans += k *8
79
+
k +=1
80
+
ans += k * (n %8)
81
+
return ans
70
82
```
71
83
72
84
```java
73
-
85
+
classSolution {
86
+
publicintminimumPushes(Stringword) {
87
+
int n = word.length();
88
+
int ans =0, k =1;
89
+
for (int i =0; i < n /8; ++i) {
90
+
ans += k *8;
91
+
++k;
92
+
}
93
+
ans += k * (n %8);
94
+
return ans;
95
+
}
96
+
}
74
97
```
75
98
76
99
```cpp
77
-
100
+
classSolution {
101
+
public:
102
+
int minimumPushes(string word) {
103
+
int n = word.size();
104
+
int ans = 0, k = 1;
105
+
for (int i = 0; i < n / 8; ++i) {
106
+
ans += k * 8;
107
+
++k;
108
+
}
109
+
ans += k * (n % 8);
110
+
return ans;
111
+
}
112
+
};
78
113
```
79
114
80
115
```go
116
+
func minimumPushes(word string) (ans int) {
117
+
n := len(word)
118
+
k := 1
119
+
for i := 0; i < n/8; i++ {
120
+
ans += k * 8
121
+
k++
122
+
}
123
+
ans += k * (n % 8)
124
+
return
125
+
}
126
+
```
81
127
128
+
```ts
129
+
function minimumPushes(word:string):number {
130
+
const n =word.length;
131
+
let ans =0;
132
+
let k =1;
133
+
for (let i =0; i< ((n/8) |0); ++i) {
134
+
ans+=k*8;
135
+
++k;
136
+
}
137
+
ans+=k* (n%8);
138
+
returnans;
139
+
}
82
140
```
83
141
84
142
<!-- tabs:end -->
Collapse file: solution/3000-3099/3014.Minimum Number of Pushes to Type Word I/Solution.cpp
0 commit comments