leetcode : 344. Reverse String
1400 ワード
タイトルラベル
string
問題の難易度
easy
タイトルアドレス:
https://leetcode.com/problems/reverse-string/
タイトルの説明:
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
問題を解く構想.タイトルが入ってくるのはcharタイプの配列で、空間複雑度O(1)が要求されるので、私が考えているのは:片側の配列を遍歴して、首尾を位置を変えることができて、配列が半分遍歴する時、配列はつまり位置を交換して完成して、停止することができます. が位置を交換する場合、空間複雑度がO(1)になるように、追加の変数を用いて交換する.
コード実装
Java
string
問題の難易度
easy
タイトルアドレス:
https://leetcode.com/problems/reverse-string/
タイトルの説明:
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
問題を解く構想.
コード実装
Java
class Solution {
public void reverseString(char[] s) {
int middle = s.length >> 1;
for (int i = 0; i < middle; i++) {
swap(s, i, s.length - 1 - i);
}
}
private void swap(char[] s, int start, int end) {
char tmp = ' ';
tmp = s[start];
s[start] = s[end];
s[end] = tmp;
}
}