-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathReverseString.java
68 lines (59 loc) · 1.75 KB
/
ReverseString.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package cn.codepub.algorithms.strings;
import cn.codepub.algorithms.utils.StackX;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* <p>
* Created with IntelliJ IDEA. 2016/1/8 19:32
* </p>
* <p>
* ClassName:ReverseString
* </p>
* <p>
* Description:反转字符串,例如abc->cba
* </P>
*
* @author Wang Xu
* @version V1.0.0
* @since V1.0.0
*/
public class ReverseString {
private String input;
private String output = "";//默认是null,所以此处将""赋值给它
public ReverseString(String in) {
input = in;
}
public String doRev() {
int stackSize = input.length();
StackX<Character> theStack = new StackX(stackSize);
for (int j = 0; j < input.length(); j++) {
char ch = input.charAt(j);
theStack.push(ch);
}
while (!theStack.isEmpty()) {
char ch = theStack.pop();
output = output + ch;
}
return output;
}
public static String getString() throws Exception {
InputStreamReader isr = new InputStreamReader(System.in, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
public static void main(String[] args) throws Exception {
String input, output;
while (true) {
System.out.println("Enter a String:");
System.out.flush();
input = ReverseString.getString();
if (input.equals("")) {
break;
}
ReverseString reverse = new ReverseString(input);
output = reverse.doRev();
System.out.println("Reversed:" + output);
}
}
}