編寫一個函數(shù),其作用是將輸入的字符串反轉(zhuǎn)過來。輸入字符串以字符數(shù)組 char[] 的形式給出。
不要給另外的數(shù)組分配額外的空間,你必須原地修改輸入數(shù)組、使用 O(1) 的額外空間解決這一問題。
你可以假設(shè)數(shù)組中的所有字符都是 ASCII 碼表中的可打印字符。文章來源:http://www.zghlxwxcb.cn/news/detail-708664.html
示例 1:
輸入:["h","e","l","l","o"]
輸出:["o","l","l","e","h"]文章來源地址http://www.zghlxwxcb.cn/news/detail-708664.html
import java.util.Arrays;
public class Reverse {
public char[] reverseString(char[] s) {
int l = 0;
int r = s.length - 1;
while (l < r) {
char temp = s[l];
s[l] = s[r];
s[r] = temp;
l++;
r--;
}
return s;
}
public static void main(String[] args) {
char[] s = {'h','e','l','l','o'};
Reverse reverse = new Reverse();
char[] res = reverse.reverseString(s);
System.out.print(Arrays.toString(res));
}
}
到了這里,關(guān)于代碼隨想錄--字符串-反轉(zhuǎn)字符串的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!