首页 > 试题广场 >

移动字母

[编程题]移动字母
  • 热度指数:3362 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个只包含小写字母的字符串s,牛牛想将这个字符串中的所有'a'字母全部移动到字符串的末尾,而且保证其它字符的相对顺序不变。其中字符串s的长度<=1e6。

示例1

输入

"abcavv"

输出

"bcvvaa"
采用双指针指向的方式,一个指向当前最靠近的a字符,另一个指向普通的字符,两者交换即可。
public String change (String s) {
        // write code here
        int i = 0;
        int j = 0;
        char[] buffer = s.toCharArray();
        for(;i<s.length();){
            if(buffer[i] != 'a'){
                char a = buffer[i];
                buffer[i] = buffer[j];
                buffer[j] = a;
                j++;
            }
            i++;
        }
        return new String(buffer);
    }

发表于 2021-06-15 23:00:46 回复(0)
public class Solution {
    public String change (String s) {
        return s.replace("a","")+s.replaceAll("[^a]","");
    }
}
发表于 2020-07-23 12:49:23 回复(0)
/**
 * 
 * @param s string字符串 
 * @return string字符串
 */
char* change(char* s ) {
    // write code here
   int k=0,i=0,n=0;
    int m=strlen(s);
    while(i<m)
    {
        if(s[i]!='a')
        s[k++]=s[i];
        else
          n++;  
        i++;
    }
    for(int i=0;i<n;i++)
        s[k++]='a';
    return s;
}
发表于 2021-09-09 22:56:04 回复(0)
#
# 
# @param s string字符串 
# @return string字符串
#
class Solution:
    def change(self , s ):
        # write code here  
        num=0
        l2=[]
        for n in s:
          if 'a' ==n:
             num+=1
          else:
            l2.append(n)
        str2=''.join(l2)+'a'*num
        return str2
发表于 2021-06-30 14:07:23 回复(0)
class Solution:
    def change(self , s ):
        q,w,e=s.split('\"')
        count=0
        a=''
        for i in range(len(w)):
            if w[i] != 'a':
                a+=w[i]
                count+=1
        a+='a'*(len(w)-count)
        return a

发表于 2021-06-18 02:02:48 回复(0)

找不到写golang的

func change(s string) string {
    b := []byte(s)
    nb := []byte{}
    count := 0
    for i := 0; i < len(b); i++ {
        if b[i] == 97 {
            count++
        } else {
            nb = append(nb, b[i])
        }
    }
    for j := 0; j < count; j++ {
        nb = append(nb, 97)
    }
    sb := string(nb)
    return sb
}
发表于 2021-06-04 21:48:24 回复(0)
本题应该考察在原先字符数组上做移动,不允许额外空间
那么直接遍历每一个元素,若不为a 且前面为a就一直交换,将前面部分的a全部移动过来。
 string change(string s) {
        // write code here
        for(int i=0;i<s.size();i++)
        {
            if(s[i]=='a')
                continue;
            else
            {
                int temp=i;//记录下交换前的i
                while(i-1>=0 && s[i-1]=='a')  //若前面为'a'那么一直交换
                {
                    s[i-1]=s[i];
                    s[i]='a';
                    i--;
                } 
                i=temp;  
            }  
        }
        return s;
    }


编辑于 2020-09-24 20:12:34 回复(0)
python两行代码解决
#
# 
# @param s string字符串 
# @return string字符串
#
class Solution:
    def change(self , s ):
        # write code here
        n = s.count('a')
        return s.replace('a','')+'a'*n


发表于 2020-09-19 13:54:44 回复(1)
源字符串中非'a'字符 按顺序取出到一个新的字符串中或者字符数组,然后末尾补齐缺省的'a'字符 或者 在源字符串上操作,定义一个下标,遇到第一个'a'记录下标位置 之后的非'a'字符位置的字符填充到该位置 下标+1
编辑于 2020-08-30 10:37:37 回复(1)
class Solution:
    def change(self , s ):
        list1=list(s)
        for i in list1:
            if(i=='a'):
                list1.remove(i)
                list1.append('a')
        st=[str(i) for i in list1]
        st1=''.join(st)
        print(st1)
a=Solution()
a.change(input())
通过率为0什么鬼,把测试数据放到本地IDE可以正确运行
发表于 2020-08-17 18:07:15 回复(1)
class Solution11 {
public:
	/**
	 *
	 * @param s string字符串
	 * @return string字符串
	 */
	string change(string s) {
		// write code here
		int count = 0;
		string str;
		int len = s.size();
		for (int i = 0; i < s.size(); i++)
		{
			if (s.at(i) == 'a')
			{
				count++;
			}
			else
			{
				str += s.at(i);
			}
		}
		str.append(count, 'a');
		return str;
	}
};

发表于 2020-08-06 17:31:11 回复(0)
class Solution:
    '''
    借助一个stack将'a'临时存入
    '''
    def change(self , s ):
        # write code here
        if not s:
            return []
        stack, res = [], []
        for c in s:
            if c == 'a':
                stack.append(c)
            else:
                res.append(c)
        
        return ''.join(res+stack)


class Solution:
    '''
    统计'a'的数量
    '''
    def change(self , s ):
        # write code here
        if not s:
            return []
        res = []
        count = 0
        for c in s:
            if c == 'a':
                count += 1
            else:
                res.append(c)
        
        s = ''.join(res) + ''.join(['a']*count)
        # s = ''.join(res)
        # for _ in range(count):
        #     s += 'a' #数据量很大时,不要用 + ,占用大量内存
        return s

发表于 2020-08-06 11:37:26 回复(0)
C++解答
string change(string s) {
        // write code here
    int nums = 0, i = 0;
	nums = s.size();
	string p(nums, ' ');
    --nums;
	for (char ch: s)
	{
		if (ch == 'a')
			p[nums--] = 'a';
		else
			p[i++] = ch;
	}
	return p;
}


发表于 2020-07-27 17:18:46 回复(0)
import java.util.*;
public class Solution {
    public String change (String s) {
        // write code here
        int len1=s.length();
        s=s.replace("a","");
        int len2=s.length();
        while(len2<len1)
        {
            s+="a";
            len2++;
        }
        return s;
        }
    }



问题是运行超时了,搞不懂,求大佬解惑
编辑于 2020-07-27 09:14:57 回复(1)
class Solution:
    def change(self, s):
        ls = [*s]
        i, j, length = 0, 0, len(ls)
        for i in range(length):
            if ls[i] != 'a':
                ls[j] = ls[i]
                j += 1
        while j < length:
            ls[j] = 'a'
            j += 1
        return ''.join(ls)

发表于 2020-07-21 22:05:23 回复(0)
class Solution {
public:
    /**
     * 
     * @param s string字符串 
     * @return string字符串
     */
    string change(string s) {
        // write code here
        int len=s.length();
        int j=0;
        string res="";
        for(int i=0;i<len;i++)
        {
            if(s[i]!='a')
            {
                s[j]=s[i];
                j++;
            }
        }
        res=s.substr(0,j);
        for(int i=0;i<len-j;i++)
        {
            res+='a';
        }
        return res;
    }
};
根据移除数字发散到字符,一个类型的题目,要多多注意发散思维
发表于 2020-07-21 16:04:16 回复(0)
// 使用StringBuilder ,统计a的个数

    public String change (String s) {
        StringBuilder sb = new StringBuilder();
        int cnt = 0;
        for(char c : s.toCharArray()){
            if(c == 'a'){
                cnt++;
            }else{
                sb.append(c);
            }
        }
        while(cnt-->0){
            sb.append('a');
        }
        return sb.toString();
    }


发表于 2020-07-20 21:51:07 回复(0)
class Solution:
    def change(self , s ):
        # write code here
        ret1 = []
        ret2 = []
        for i in range(len(s)):
            if s[i] == 'a':
                ret1.append(s[i])
            else:
                ret2.append(s[i])
        res1 = "".join(ret2)
        res2 = "".join(ret1)
        res = res1 + res2
        return res

发表于 2020-07-18 23:09:20 回复(0)

import java.util.*;
 
 
public class Solution {
    
    public static void main(String [] args){
        Scanner scan = new Scanner(System.in);
        String s = scan.next();
        System.out.print(change(s));
    }
    /**
     * 
     * @param s string字符串 
     * @return string字符串
     */
    public static String change (String s) {
        int len = s.length();
        s = s.replace("a", "");
        int num = len - s.length();
        for(int i=0; i < num; i++){
            s+="a";
        }
        return s;
    }
}
提示为 :运行超时:您的程序未能在规定时间内运行结束,请检查是否循环有错或算法复杂度过大。
case通过率为90.00%,求大佬讲解
发表于 2020-07-18 11:47:30 回复(2)

问题信息

难度:
19条回答 4397浏览

热门推荐

通过挑战的用户

查看代码