#include <stdio.h>
#include <vector>
#include <algorithm>
#include <math.h>
#include <queue>

using namespace std;

int checkTable[59049];

struct Data{
	int number,depth;
};

int getNum(char ch){
	switch(ch){
	case 'r':return 0;
	case 'g':return 1;
	case 'b':return 2;
	}
	return -1; //must not reach here
}

int getWeight(int w){
	switch(w){
	case 0:return 1;
	case 1:return 3;
	case 2:return 9;
	case 3:return 27;
	case 4:return 81;
	case 5:return 243;
	case 6:return 729;
	case 7:return 2187;
	case 8:return 6561;
	case 9:return 19683;
	}
	return -1;	//must not reach here
}

int translateData(char table[],int size){
	int ret = 0;

	for(int i = 0; i < size; i++){
		ret += getNum(table[i])*pow(3,(size-1)-i);
	}

	return ret;
}

void setData(char warm[],int code,int size){
	int tmp;
	for(int i = 0; i < size; i++){
		tmp = code/getWeight(size-1-i);
		if(tmp == 0){
			warm[i] = 'r';
		}else if(tmp == 1){
			warm[i] = 'g';
		}else{
			warm[i] = 'b';
		}
		code %= getWeight(size-1-i);
	}
}

int dfs(char warm[],int size){

	int ret = -1;
	Data data;
	data.number = translateData(warm,size);
	data.depth = 0;

	queue<Data> Q;
	Q.push(data);

	Data tmp;
	char tmp_warm[11], next_warm[11];
	int code;

	while(!Q.empty()){
		tmp = Q.front();
		Q.pop();

		setData(tmp_warm,tmp.number,size);

		bool FLG = true;
		for(int i = 0; i < size-1; i++){
			if(tmp_warm[i] != tmp_warm[i+1]){
				FLG = false;
				break;
			}
		}
		if(FLG){
			while(!Q.empty())Q.pop();
			ret = tmp.depth;
			break;
		}

		for(int i = 0; i < size-1; i++){
			if(tmp_warm[i] != tmp_warm[i+1]){
				Data new_data;
				for(int k = 0; k < size; k++)next_warm[k] = tmp_warm[k];

				if(tmp_warm[i] != 'r' && tmp_warm[i+1] != 'r'){
					next_warm[i] = 'r';
					next_warm[i+1] = 'r';
				}else if(tmp_warm[i] != 'g' && tmp_warm[i+1] != 'g'){
					next_warm[i] = 'g';
					next_warm[i+1] = 'g';
				}else{
					next_warm[i] = 'b';
					next_warm[i+1] = 'b';
				}

				code = translateData(next_warm,size);
				if(checkTable[code] == -1){
					checkTable[code] = 1;
					new_data.number = code;
					new_data.depth = tmp.depth+1;
					Q.push(new_data);
				}
			}
		}
	}
	return ret;
}

int main(){

	int size,minimum;
	char buf[11];

	while(true){
		scanf("%s",buf);
		if(buf[0] == '0')break;

		for(size = 0;buf[size] != '\0';size++);

		for(int i = 0; i < 59049; i++)checkTable[i] = -1;

		checkTable[translateData(buf,size)] = 1;

		minimum = dfs(buf,size);

		if(minimum == -1)printf("NA\n");
		else{
			printf("%d\n",minimum);
		}
	}

    return 0;
}