题目
翻转字符串
java代码
package com.lizhouwei.chapter5;
/**
* @Description: 翻转字符串
* @Author: lizhouwei
* @CreateDate: 2018/4/25 20:09
* @Modify by:
* @ModifyDate:
*/
public class Chapter5_11 {
public String reverse(String str) {
if (str == null) {
return null;
}
char[] chars = str.toCharArray();
reverse(chars, 0, chars.length - 1);
int start = -1;
int end = -1;
for (int i = 0; i < chars.length; i++) {
if (chars[i] != ' ') {
start = i == 0 || chars[i - 1] == ' ' ? i : start;
end = i == chars.length - 1 || chars[i + 1] == ' ' ? i : end;
}
if (start != -1 && end != -1) {
reverse(chars, start, end);
start = -1;
end = -1;
}
}
return String.valueOf(chars);
}
public String reverseByK(String str,int k) {
if (str == null) {
return null;
}
char[] chars = str.toCharArray();
reverse(chars, 0,k-1);
reverse(chars, k,chars.length - 1);
reverse(chars, 0, chars.length - 1);
return String.valueOf(chars);
}
public void reverse(char[] chars, int start, int end) {
char temp = ' ';
while (start < end) {
temp = chars[start];
chars[start++] = chars[end];
chars[end--] = temp;
}
}
//测试
public static void main(String[] args) {
Chapter5_11 chapter = new Chapter5_11();
String str1 = "dog loves pig";
String result1 = chapter.reverse(str1);
System.out.println("dog loves pig 翻转:" + result1);
String str2 = "1234567ABCD";
String result2 = chapter.reverseByK(str2,7);
System.out.println("1234567ABCD 左半区和右半区调整:" + result2);
}
}
结果