字符串为*号和26个字母、阿拉伯数字的任意组合,把*号都移动到最左侧,把其他字母和数字都移到最右侧并保持相对顺序不变,返回字符*的个数,要求时间和空间复杂度最小。
第一种方法:跟上面的重排问题是一样的
- int MoveStar(char *str , int n)
- {
- int i , j = n-1;
- for(i = n - 1 ; i >= 0 ; --i)
- {
- if(str[i] != '*')
- {
- if(str[j] == '*')
- {
- str[j] = str[i];
- str[i] = '*';
- }
- --j;
- }
- }
- return j+1;
- }
- int MoveStar(char *str , int n)
- {
- int i , count = 0;
- for(i = n - 1 ; i >= 0 ; --i)
- {
- if(str[i] == '*')
- ++count;
- else if(count > 0) // str[i] != '*'
- str[i + count] = str[i];
- }
- for(i = 0 ; i < count ; ++i)
- str[i] = '*';
- return count;