Write a function that reverses a string. The input string is given as an array of characters
s
. You must do this by modifying the input array in-place withO(1)
extra memory.
給定字串s
,將其翻轉
最直接想法就是直接使用新的一個字串,並從尾到頭歷遍字串,但是需要O(n)
的空間,因此如果使用雙指標法的話就不需要這麼多空間,直接交換頭尾兩個指標的字元就好
i
和j
,直到i == j
s[i]
與s[j]
i++
與j--
O(n)
char
來暫存交換的字元void reverseString(char* s, int sSize) {
for (int i = 0, j = sSize - 1; i < j; i++, j--){
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
class Solution {
public:
void reverseString(vector<char>& s) {
for (int i = 0, j = s.size(); i < j; i++, j--){
swap(s[i], s[j - 1]);
}
}
};
class Solution {
public:
void reverseString(vector<char>& s) {
for (int i = 0, j = s.size() - 1; i < j; i++, j--){
swap(s[i], s[j]);
}
}
};
or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Do you want to remove this version name and description?
Syncing