RGB问题

RGB问题

  • 一、 3颜色

    给一个字符串 由RGB(红绿蓝)3种字母组成

    1. 找出串中最长的相同子串,输出字母以及所在位置,然后剔除(如有多个相同拿最左的子串)

    2. 将剩余部分按序连接,如果只有一个字母则结束游戏,否则返回第一步

    3. 注意每次输出的位置为原始串中的位置

例:

RBBGGR

B 2 3

G 4 5

R 1 6



import java.util.HashMap;

public class RGB {
	public void findMax(String s){
		int curIndex = 0;
		int curCount = 1;
		int maxIndex = -1;
		int maxCount = 0;
		int[][] pos = new int[3][s.length()];
		char[] sArray = s.toCharArray();
		int visited = 0;
		boolean[] isVisited = new boolean[sArray.length];
		int i = 0;
		int p0 =0;int p1 = 0;int p2 = 0;
		HashMap<Character,Integer> map = new HashMap<Character, Integer>();
		map.put('R', 0);
		map.put('G', 1);
		map.put('B', 2);
		
		for(int m = 0;m<s.length();m++){
			if(sArray[m]=='R') pos[0][p0++] = m+1;
			if(sArray[m]=='G') pos[1][p1++] = m+1;
			if(sArray[m]=='B') pos[2][p2++] = m+1;
		}
		while(visited!=sArray.length){
			while(i<sArray.length){
				if(isVisited[i]){
					i++;
					continue;
				}
				curIndex = i;
				int j = curIndex+1;
				while(j<sArray.length){
					if(isVisited[j]){
						j++;
						continue;
					}
					if(sArray[curIndex] == sArray[j]){
						curCount++;
						//System.out.println(curCount+"");
						if(curCount>maxCount){
							maxCount = curCount;
							maxIndex = curIndex;
						}
						j++;
					}else{
						if(curCount>maxCount){
							maxCount = curCount;
							maxIndex = curIndex;
						}
						break;
					}
				}
				curCount=1;
				if(curCount>maxCount){
					maxCount = curCount;
					maxIndex = curIndex;
				}
				i++;
			}
			i=0;
			visited+=maxCount;
			for(int k = maxIndex;k<(maxIndex+maxCount);k++){
				isVisited[k] = true;
			}
			System.out.print(sArray[maxIndex]+"");
			for(int c = 0;c<s.length();c++){
				if(pos[map.get(sArray[maxIndex])][c] == (maxIndex+1)){
					for(int m = 0;m<maxCount;m++){
						System.out.print(" "+pos[map.get(sArray[maxIndex])][c+m]);
					}
					break;
				}
			}
			System.out.println();
			maxCount = 0;
			maxIndex = -1;
		}
	}
}

猜你喜欢

转载自www.cnblogs.com/lvgj/p/12597703.html
RGB