本篇同步發布於Blog:[解題] LeetCode - 344 Reverse String
LeetCode
344 - Reverse String
https://leetcode.com/problems/reverse-string/
給一個字串s,在不使用額外記憶體的條件,將字串裡的字元做反轉。
建立一個索引值i,從0開始到字串長度的一半len/2,再將s[i]與s[len-i-1]做交換。
難度為Easy
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void reverseString(vector<char>& s) {
for(int i = 0 ; i < s.size() / 2;++i){
char temp = s[i];
s[i] = s[s.size()-i-1];
s[s.size()-i-1] = temp;
}
}
};
int main() {
vector<char> s{'h','e','l','l','o'};
Solution sol;
sol.reverseString(s);
for(char c : s){
cout << c << " ";
}
return 0;
}
using System;
namespace LeetCode344
{
public class Solution {
public void ReverseString(char[] s) {
int mid = s.Length / 2;
for(int i = 0 ; i < s.Length / 2;++i){
char a = s[i];
s[i] = s[s.Length - i - 1];
s[s.Length-i-1] = a;
}
}
}
public class Program
{
public static void Main()
{
Solution sol = new Solution();
char[] s = new char[]{'h', 'e', 'l', 'l', 'o'};
sol.ReverseString(s);
foreach(char c in s)
{
Console.Write(c + " ");
}
Console.Read();
}
}
}
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%2B%2B/300-399/344.cpp
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%23/300-399/344.cs