新农上路
- 积分
- 99
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2013-3-23
- 最后登录
- 1970-1-1
|
public static void main(String[] args) {
String[] a1 = {"this", ",", "is", "a", "word", "."};
String b = reverseString1(a1);
System.out.println(b);
}
public static String reverseString1(String[] s) {
Stack<String> stack1= new Stack<String>();
Stack<String> stack2= new Stack<String>(); //仅存储
StringBuilder res = new StringBuilder(); //输出用
Map<Integer, String> map = new HashMap<Integer, String>();//存储标点位置
for (int i = 0; i <= s.length - 1; i++) {
if (s[i].equals(",") || s[i].equals(".")) {
if (s[i].equals(",")){
map.put(i, ",");
continue;
} else if (s[i].equals(".")) {
map.put(i, ".");
continue;
}
}
stack1.push(s[i]);
}
for (int i = 0; i <= s.length - 1; i++) {
if (map.containsKey(i)) {
String temp = map.get(i);
stack2.push(temp);
res.append(temp).append(" ");
continue;
}
if (map.containsKey(i + 1)) {//如果下一个是标点的话,后面就不要加空格了
res.append(stack1.peek());
stack2.push(stack1.pop());
} else {
res.append(stack1.peek()).append(" ");
stack2.push(stack1.pop());
}
}
return res.toString();
} |
|