翻转单词顺序列
翻转单词顺序列
https://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3?tpId=13&&tqId=11197&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
先将每个单词翻转,然后再将整个字符数组翻转
char[] s = {am. I}
每个单词翻转
char[] s = {.ma I}
整个翻转 char[] s = {I am.}
public String ReverseSentence(String str) { int n = str.length(); int i = 0, j = 0; char[] s = str.toCharArray(); while(j <= n){ if(j == n || s[j] == ' '){ reverse(s,i,j-1); i = j+1; } j++; } reverse(s,0,n-1); return new String(s); } public void reverse(char[] s,int i, int j){ while(i<j) swap(s,i++,j--); } public void swap(char[] s,int i, int j){ char tmp = s[i]; s[i] = s[j]; s[j] = tmp; }
剑指offer 文章被收录于专栏
为刷过的每一道题都书写一篇题解,便于重复练习~