题目如下
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;i<str.length();i++){
if(i==0&&!"*".equals(str.substring(i,i+1))&&
!"*".equals(str.substring(i+1,i+2)))
result+=str.substring(i,i+1);
if(i>0&&i<str.length()-1&&
!"*".equals(str.substring(i,i+1))&&
!"*".equals(str.substring(i+1,i+2))&&
!"*".equals(str.substring(i-1,i)))
result+=str.substring(i,i+1);
if(i==str.length()-1&&
!"*".equals(str.substring(i,i+1))&&
!"*".equals(str.substring(i-1,i)))
result+=str.substring(i,i+1);
}
return result;
}
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;
}
也可以用正则表达式来完成。