java面试题之 使用两个int翻转字符串

来源:互联网 发布:尼康官方调焦软件 编辑:程序博客网 时间:2024/05/23 14:03

源自http://bbs.csdn.net/topics/390780969

此处贴出自己实现的代码;


内容:

有一个对象 StringBuilder sentence = new StringBuilder("This is an apple"); 
要求只使用 char c,int p1,int p2这三个变量,且不再开辟更多内存的情况下,输出 apple an is This


StringBuffer str = new StringBuffer("This is an apple");int p1 = str.length() - 1;int p2;char c;while (p1 >= 0) {c = str.charAt(p1);while (c != ' ' && p1 > 0) {c = str.charAt(--p1);}if (c != ' ') {System.out.print(' ');}System.out.print(c);p2 = p1;c = str.charAt(++p2);while (c != ' ' && p2 < str.length()) {c = str.charAt(p2++);if (c != ' ') {System.out.print(c);}}p1--;


0 0
原创粉丝点击