字符串
空格替换:请实现一个函数,把字符串 s
class Solution { public String replaceSpace(String s) { int length = s.length(); char [] array = new char[length * 3]; int size = 0; for (int i = 0; i < length; i++) { char c = s.charAt(i); if (c == ' ') { array[size++] = '%'; array[size++] = '2'; array[size++] = '0'; } else { array[size++] = c; } } String newStr = new String(array, 0, size); return newStr; } }
左旋转字符串:
class Solution { public String reverseLeftWords(String s, int n) { int len = s.length(); StringBuilder sb = new StringBuilder(s); reverseString(sb, 0 ,n - 1); reverseString(sb, n , len-1); return sb.reverse().toString(); } public void reverseString(StringBuilder sb, int start, int end) { while (start < end) { char tmp = sb.charAt(start); sb.setCharAt(start,sb.charAt(end)); sb.setCharAt(end,tmp); start++; end--; } } }
StringBuilder实现了父类AbstractStringBuilder中的setCharAt()方法.
这里还借助了其父类的reverse方法:直接反转整个字符串。
2、切片:使用substring方法:
class Solution { public String reverseLeftWords(String s, int n) { return s.substring(n, s.length()) + s.substring(0, n); } }