JAVA实现starOut(codingbat)

题目如下

Return a version of the given string, where for every star (*) in the string the star and the chars immediately to its left and right are gone. So "ab*cd" yields "ad" and "ab**cd" also yields "ad".

starOut("ab*cd") → "ad"
starOut("ab**cd") → "ad"
starOut("sm*eilly") → "silly"

我的代码

public String starOut(String str) {
  String result = "";
  if(str.length()==1){
    return "*".equals(str)?"":str;
  }
  for(int i=0;i0&&i

StackOverflow上的大哥给的答案

public String starOut(String str)
{
    String ret = "";
    for (int i = 0; i < str.length(); i++)
    {        
        if (!( '*' == str.charAt(i) 
        || i + 1 < str.length() && '*' == str.charAt(i+1)
        || i > 0 && '*' == str.charAt(i-1) ))
        {
            ret = ret + str.charAt(i);
        }        
    }
    return ret;
}

前两个思路差不多,下面是另外一个思路的做法。

public String starOut(String str) {
  int len = str.length();
  String finalString = "";
  
  for (int i = 0; i < len; i++) {
    if (i == 0 && str.charAt(i) != '*')
      finalString += str.charAt(i);
  
    if (i > 0 && str.charAt(i) != '*' && str.charAt(i-1) != '*')
      finalString += str.charAt(i);
      
    if (i > 0 && str.charAt(i) == '*' && str.charAt(i-1) != '*')
      finalString = finalString.substring(0,finalString.length()-1);
      
  }
  return finalString;
}

也可以用正则表达式来完成。

你可能感兴趣的:(JAVA实现starOut(codingbat))