算法天天练334:字符串翻转
题目来源: https://leetcode.com/problems/reverse-string/
问题描述: 颠倒一个char数组里面的字符串顺序,只能修改原始数组的值,不允许分配额外的空间。
举例说明:
输入 | 输出 |
---|---|
["h","e","l","l","o"] | ["o","l","l","e","h"] |
["H","a","n","n","a","h"] | ["h","a","n","n","a","H"] |
解决方案
- 遍历数组后用中间变量交换元素位置,时间复杂度Ο(n)
class Solution {
public void reverseString(char[] s) {
int length = s.length;
for(int i=0;i<length;i++) {
if(i < (length-i-1)) {
char temp = s[i];
s[i] = s[length-i-1];
s[length-i-1] = temp;
}
}
}
}
博客作者:编码专家
公 众 号:编码专家
独立博客:codingbrick.com
文章出处:https://www.cnblogs.com/xiaoyangjia/p/11684467.html
本文版权归作者所有,任何人或团体、机构全部转载或者部分转载、摘录,请在文章明显位置注明作者和原文链接。
公 众 号:编码专家
独立博客:codingbrick.com
文章出处:https://www.cnblogs.com/xiaoyangjia/p/11684467.html
本文版权归作者所有,任何人或团体、机构全部转载或者部分转载、摘录,请在文章明显位置注明作者和原文链接。