题目
分析
下标和空格结合划分字符串
代码实现
自己的解法
class Solution { public String reverseWords(String s) { if(s==null||s.length()==0) return ""; //去掉前后空格 int i = 0; int j = 0; for (i = 0; i < s.length(); i++) { if (s.charAt(i) != ' ') break; } for (j = s.length() - 1; j > -1; j--) { if (s.charAt(j) != ' ') break; } if(i==s.length()) return ""; s = s.substring(i, j + 1); s = reverse(s, 0, s.length() - 1); int start = -1; int end = -1; StringBuilder sb = new StringBuilder(); for (i = 0; i < s.length(); i++) { if(s.charAt(i)==' ') continue; start = (i == 0 || s.charAt(i - 1) == ' ') ? i : start; end = (i == s.length() - 1 || s.charAt(i + 1) == ' ') ? i : end; if (start != -1 && end != -1) { String temp = reverse(s, start, end); if (end != s.length() - 1) sb.append(temp + " "); else sb.append(temp); start = -1; end = -1; } } return sb.toString(); } public String reverse(String s, int start, int end) { String temp = s.substring(start, end + 1); char[] chas = temp.toCharArray(); start = 0; end = chas.length - 1; while (start < end) { char t = chas[start]; chas[start] = chas[end]; chas[end] = t; start++; end--; } return String.valueOf(chas); } }
学习情况
1次