344. 反转字符串:
s
原地

样例 1:

输入:
	s = ["h","e","l","l","o"]
	
输出:
	["o","l","l","e","h"]

样例 2:

输入:
	s = ["H","a","n","n","a","h"]
	
输出:
	["h","a","n","n","a","H"]

提示:

  • 1 <= s.length <= 105
  • s[i] 都是 ASCII 码表中的可打印字符

原题传送门:

分析
  • 面对这道算法题目,二当家的陷入了沉思。
  • 反转字符串是比较常用的操作,有API当然用API,没有API的话就按照中心对称进行头尾逐个字符的交换即可。
题解

rust

impl Solution {
    pub fn reverse_string(s: &mut Vec<char>) {
        s.reverse()
    }
}

go

func reverseString(s []byte)  {
    for l, r := 0, len(s)-1; l < r; l, r = l+1, r-1 {
		s[l], s[r] = s[r], s[l]
	}
}

c++

class Solution {
public:
    void reverseString(vector<char>& s) {
        std::reverse(s.begin(), s.end());
    }
};

java

class Solution {
    public void reverseString(char[] s) {
        for (int l = 0, r = s.length - 1; l < r; ++l, --r) {
            char t = s[l];
            s[l] = s[r];
            s[r] = t;
        }
    }
}

python

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        s.reverse()

非常感谢你阅读本文~
欢迎【点赞】【收藏】【评论】~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://le-yi.blog.csdn.net/ 博客原创~