题解 | #字符逆序#
字符逆序
http://www.nowcoder.com/practice/cc57022cb4194697ac30bcb566aeb47b
- HJ31 单词倒排基础上修改即可
- 思路注释在代码
import java.io.*;
import java.util.Stack;
public class Main {
public static void main(String[] args) throws IOException {
// String str = "$bo*y gi!r#l";
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String str = bufferedReader.readLine();
char[] chars = str.toCharArray();
StringBuilder stringBuilder = new StringBuilder();
Stack<String> stack = new Stack();
/**
* 字符串转数组遍历
*/
for (int i = 0; i < chars.length; i++) {
/**
* 若是字符则保存
*/
if (Character.isLetter(chars[i]) && i <= chars.length - 1) {
stringBuilder.append(chars[i]);
}
/**
* 若不是字符则添加之前保存的字符串,并添加该字符
*/
else if (!Character.isLetter(chars[i]) && stringBuilder.length() != 0) {
stack.push(mothod(stringBuilder.toString()));
stack.push(String.valueOf(chars[i]));
stringBuilder = new StringBuilder();
}
/**
* 若不是字符且无缓存的字符串,则添加该字符
*/
else if (!Character.isLetter(chars[i]) && stringBuilder.length() == 0) {
stack.push(String.valueOf(chars[i]));
}
/**
* 单独添加最后的
*/
if (i == chars.length - 1 && stringBuilder.length() != 0) {
stack.push(mothod(stringBuilder.toString()));
}
}
/**
* 逆序输出
*/
while (!stack.isEmpty()) {
if (stack.size() != 1) {
System.out.print(stack.pop());
} else {
System.out.print(stack.pop());
}
}
}
/**
* 翻转字符串
* @param str
* @return
*/
public static String mothod(String str) {
StringBuilder stringBuilder = new StringBuilder();
char[] chars = str.toCharArray();
for (int i = chars.length - 1; i >= 0; i--) {
stringBuilder.append(chars[i]);
}
return stringBuilder.toString();
}