登 录
将字符串中的字符“*”移动到串的前面,前面的肺“*”字符后移,但不能改变非“*”字符的先后顺序,函数返回串中字符“*”的数量:
public class Move { public static void main(String []args) throws IOException{ Scanner sc = new Scanner(System.in); String str = sc.next(); int count = 0; char []cary = str.toCharArray(); for(int i = 0;i<cary.length;i++){ if(cary[i]=='*'){ count++; for(int j = i;j > 0;j--){ cary[j]=cary[j-1]; } cary[0] = '*'; } } for(char c :cary){ System.out.print(c); } System.out.println(); System.out.println(count); } }
//结果是: //555***4444/*/***111 //*******5554444//111 //7
注:在另外一个博客中好心人提的建议:
package charmove; import java.io.IOException; public class Move { public static void main(String[] args) throws IOException { String str = "555***4444/*/***111"; int num = 10000000; long t1 = System.currentTimeMillis(); for (int i = 0; i < num; i++) { move1(str); } System.out.println(move1(str)); long t2 = System.currentTimeMillis(); System.out.println("1:" + (t2 - t1)); t1 = System.currentTimeMillis(); for (int i = 0; i < num; i++) { move2(str); } System.out.println(move2(str)); t2 = System.currentTimeMillis(); System.out.println("2:" + (t2 - t1)); } public static String move1(String str) { char[] cary = str.toCharArray(); for (int i = 0; i < cary.length; i++) { if (cary[i] == '*') { for (int j = i; j > 0; j--) { cary[j] = cary[j - 1]; } cary[0] = '*'; } } return new String(cary); } public static String move2(String str) { char[] cary = str.toCharArray(); int pos = str.length() - 1; int pre = pos - 1; while (pre > -1) { if (cary[pos] != '*') { pos--; if (pos < pre) { pre = pos; } continue; } if (cary[pre] == '*') { pre--; continue; } char ch = cary[pos]; cary[pos] = cary[pre]; cary[pre] = ch; pre--; pos--; } return new String(cary); } }
速度比我的快一倍,学习了呵..
欢迎:
抱歉!评论已关闭.