字符串----交换星号

class Solution {
	public static void main(String[] args) {
		Solution test=new Solution();
		System.out.println(test.fun("*01*2234*4"));
	}
	public String fun(String s)
	{
		char[] ch=s.toCharArray();
		if(s==null)
		return null;
		//两个参数 i代表数字的下标 j代表*的下标
		//一直循环j++  i++要看条件 只有在找到*的时候 交换完毕再i++ 
		for(int i=0,j=0;j<s.length();j++)
		{
			if(s.charAt(j)=='*')
			{
				
				char temp=ch[i];
				ch[i]=ch[j];
				ch[j]=temp;
				i++;
			}
		}
		return new String(ch);
	}
}

上面的会变化数字的相对位置

下面不会变化数字的相对位置,从后往前遍历

class Solution {
	public static void main(String[] args) {
		Solution test=new Solution();
		System.out.println(test.fun("*01*2234*4"));
	}
	public String fun(String s)
	{
		char[] ch=s.toCharArray();
		if(s==null)
		return null;
		//如果要求数字的相对位置不变 需要从后往前
		for(int i=s.length()-1,j=s.length()-1;i>=0;i--)
		{
			if(s.charAt(i)>='0'&&s.charAt(i)<='9')
			{
				
				char temp=ch[i];
				ch[i]=ch[j];
				ch[j]=temp;
				j--;
			}
		}
		return new String(ch);
	}
}

猜你喜欢

转载自blog.csdn.net/ustcyy91/article/details/80108785