第八天,从昨天看,难度应该会递加,今天是五道题,稍有挑战性了。
class Solution { public void reverseString(char[] s) { int n = s.length; int i = 0; int j = n - 1; while(i<j){ char temp = s[i]; s[i] = s[j]; s[j] = temp; i++; j--; } } }
很简单双指针 首尾互换即可
class Solution { public String reverseStr(String s, int k) { int n = s.length(); StringBuffer sb = new StringBuffer(); int l = 0; while(l < n){ StringBuffer temp = new StringBuffer(); int count = (l + k > n) ? n : l + k; int jump = (l + 2*k >n ) ? n : l + 2*k; temp.append(s.substring(l, count)); sb.append(temp.reverse()); if(count < jump){ sb.append(s.substring(count, jump)); } l += 2*k; } return sb.toString(); } }
string中的char,相隔k个反转k个,如果结尾剩余的不够的话,全部反转
class Solution { public String replaceSpace(String s) { int n = s.length(); StringBuilder sb = new StringBuilder(); for(int i = 0; i<n; i++){ if(s.charAt(i)!=' '){ sb.append(s.charAt(i)); } else{ sb.append("%20"); } } return sb.toString(); } }
直接替换
class Solution { public String reverseWords(String s) { char[] s_char = s.toCharArray(); int slow = 0; int fast = 0; reverseArray(s_char, 0, s_char.length-1); reverseWord(s_char); return cleanSpace(s_char); // return new String(s_char).substring(0, s_char.length); } public void reverseArray(char[] array, int i, int j ){ while(i < j){ char temp = array[i]; array[i++] = array[j]; array[j--] = temp; } } public void reverseWord(char[] array){ int n = array.length; int i = 0; int j = 0; while (j< n ){ while( i < n && array[i] == ' '){ i++; } j = i; while(j < n && array[j] != ' '){ j++; } reverseArray(array, i, j-1); i = j; } } public String cleanSpace(char[] array){ int n = array.length; int i = 0; int j = 0; while (j < n) { while (j < n && array[j] == ' ') j++; while (j < n && array[j] != ' ') array[i++] = array[j++]; while (j < n && array[j] == ' ') j++; if (j < n) array[i++] = ' '; } return new String(array).substring(0, i); } }
先反转数组,再反转单词,再清除多余空格
class Solution { public String reverseLeftWords(String s, int n) { int size = s.length(); StringBuilder sb = new StringBuilder(); for(int i = n; i<size; i++){ sb.append(s.charAt(i)); } for(int i = 0; i< n; i++){ sb.append(s.charAt(i)); } return sb.toString(); } }
按顺序置入StringBuffer就行。
今天的题,虽然数量多,但都没什么难度,比昨天强。
标签:char,String,int,反转,II,while,字符串,array From: https://www.cnblogs.com/catSoda/p/16806046.html