算法88题

来源:互联网 发布:淘宝商家多发货 编辑:程序博客网 时间:2024/05/16 10:38

函数将字符串中的字符'*'移到串的前部分,

前面的非'*'字符后移,但不能改变非'*'字符的先后顺序,函数返回串中字符'*'的数量。
如原始串为:ab**cd**e*12,

处理后为*****abcde12,函数并返回值为5。(要求使用尽量少的时间和辅助空间)

public static int MoveStar(String s){char[] chars = s.toCharArray();int count = 0;for(int i = chars.length - 1; i >= 0; i--){if(chars[i] == '*')count++;else{if(count > 0)chars[i + count] = chars[i];}}for(int i = 0; i < count; i++)chars[i] = '*';System.out.println(chars);return count;}