題目來源: 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;
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/139444.html
標籤:其他
上一篇:數論篇1——素數問題
下一篇:演算法天天練系列匯總
