字符串消除

今日于csdn上看到一个问题:

题目详情

给定一个字符串,仅由a,b,c 3种小写字母组成。当出现连续两个不同的字母时,你可以用另外一个字母替换它,如

 

  1. 有ab或ba连续出现,你把它们替换为字母c;
  2. 有ac或ca连续出现时,你可以把它们替换为字母b;
  3. 有bc或cb 连续出现时,你可以把它们替换为字母a。

 

你可以不断反复按照这个规则进行替换,你的目标是使得最终结果所得到的字符串尽可能短,求最终结果的最短长度。

 

输入:字符串。长度不超过200,仅由abc三种小写字母组成。

输出: 按照上述规则不断消除替换,所得到的字符串最短的长度。

 

例如:输入cab,输出2。因为我们可以把它变为bb或者变为cc。

          输入bcab,输出1。尽管我们可以把它变为aab -> ac -> b,也可以把它变为bbb,但因为前者长度更短,所以输出1。

 

 

函数头部

C/C++ int minLength(const char *s);

Java:

public class Main { 

      public static int minLength(String s);

}

个人解决方法:

import java.util.ArrayList;
import java.util.List;


public class removeChar {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  String arg = "cabababbabcabaaaababacabab";
  arg = removeStr(arg);
  System.out.println(arg);
  int minLength = arg.length();
  System.out.println("最短长度是:"+minLength);
  return;
 }
 static String removeStr(String arg){
  String[] temp = arg.split("");
  List<String> tempList = new ArrayList<String>();
  for(String tempAA:temp){
   if(!tempAA.equals("")){
    tempList.add(tempAA);
   }
  }
  for(int i=0;i<tempList.size()-1;i++){
   if(i==tempList.size()-1){
    break;
   }
   if(tempList.get(i).equals("a")){
    if(tempList.get(i+1).equals("b")){
     tempList.set(i, "c");
     tempList.remove(i+1);
    }else if(tempList.get(i+1).equals("c")){
     tempList.set(i, "b");
     tempList.remove(i+1);
    }
   }else if(tempList.get(i).equals("b")){
    if(tempList.get(i+1).equals("c")){
     tempList.set(i, "a");
     tempList.remove(i+1);
    }else if(tempList.get(i+1).equals("a")){
     tempList.set(i, "c");
     tempList.remove(i+1);
    }
   }else if(tempList.get(i).equals("c")){
    if(tempList.get(i+1).equals("a")){
     tempList.set(i, "b");
     tempList.remove(i+1);
    }else if(tempList.get(i+1).equals("b")){
     tempList.set(i, "a");
     tempList.remove(i+1);
    }
   }
  }
  String newArg="";
  for(String tempBB:tempList){
   newArg += tempBB;
  }
  for(String tempCC:tempList){
   if(!tempCC.equals(tempList.get(0))){
    newArg=removeStr(newArg);
    break;
   }
  }
  return newArg;
 }
 

}

大家帮忙看看对不,有没有更好的方法解决啊!!!

原文地址:https://www.cnblogs.com/zp-xdzc/p/3304761.html