收集面試題(十二)(字串反轉)
阿新 • • 發佈:2019-01-10
字串翻轉
package StingSub;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;
public class ReverseStr {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(reverseStack("wokessd.cm .cok .ddj dd*&4 dlk"));
System.out.println(reverseDeque("wokessd.cm .cok .ddj dd*&4 dlk"));
System.out.println(reverse("wokessd.cm .cok .ddj dd*&4 dlk", "cok"));
System.out.println(reverseByInfo("wokessd.cm .cok .ddj dd*&4 dlk"));
}
public static String reverseStack(String stringInfo) {
if (stringInfo == null) {
throw new NullPointerException("info is null.");
}
StringBuffer buffer = new StringBuffer("");
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < stringInfo.length(); i++) {
stack.push(stringInfo.charAt(i));
}
while (!stack.empty()) {
buffer.append(stack.pop());
}
return buffer.toString();
}
public static String reverseDeque(String stringInfo) {
if (stringInfo == null) {
throw new NullPointerException("info is null.");
}
StringBuffer buffer = new StringBuffer("");
Deque<Character> deque = new ArrayDeque<Character>();
for (int i = 0; i < stringInfo.length(); i++) {
deque.addFirst(stringInfo.charAt(i));
}
while (!deque.isEmpty()) {
buffer.append(deque.removeFirst());
}
return buffer.toString();
}
public static String reverse(String stringInfo, String noReverse) {
if (stringInfo == null || noReverse == null) {
throw new NullPointerException("info is null.");
}
StringBuffer buffer = new StringBuffer("");
Stack<Character> stack = new Stack<Character>();
boolean iscontain = false;
for (int i = 0; i < stringInfo.length(); i++) {
iscontain = true;
for (int j = 0; j < noReverse.length(); j++) {
if ((i + j) > stringInfo.length()
|| (stringInfo.charAt(i + j) != noReverse.charAt(j))) {
iscontain = false;
break;
}
}
if (iscontain) {
for (int j = noReverse.length() - 1; j >= 0; j--) {
stack.push(noReverse.charAt(j));
}
i += noReverse.length() - 1;
} else {
stack.push(stringInfo.charAt(i));
}
}
while (!stack.empty()) {
buffer.append(stack.pop());
}
return buffer.toString();
}
public static String reverseByInfo(String stringInfo) {
if (stringInfo == null) {
throw new NullPointerException("info is null.");
}
StringBuffer buffer = new StringBuffer("");
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < stringInfo.length(); i++) {
stack.push(stringInfo.charAt(i));
}
while (!stack.empty()) {
buffer.append(stack.pop());
}
String reverseall = buffer.toString();
buffer.delete(0, buffer.length());
for (int i = 0; i < reverseall.length(); i++) {
if (reverseall.charAt(i) == ' ' || reverseall.charAt(i) == '.') {
while (!stack.empty()) {
buffer.append(stack.pop());
}
buffer.append(reverseall.charAt(i));
} else {
stack.push(reverseall.charAt(i));
}
}
while (!stack.empty()) {
buffer.append(stack.pop());
}
return buffer.toString();
}
}