【TopCoder】SRM 159 DIV2 Lv.1
SRM 159 DIV2 Lv.1
問題文概略
道路図が文字列で与えられており、車を止めることのできる場所を求める。
書いたコード
public class StreetParking { public int freeParks(String street) { String regex = "--B|-B|-D|-S-"; String replaceStreet = street.replaceAll(regex, ""); char[] s = replaceStreet.toCharArray(); int ans = 0; for(char x: s) { if(x == '-') ans++; } return ans; } }
他の参加者のコードを読んで修正した
public class StreetParking { public int freeParks(String street) { int ans = 0; int streetLength = street.length(); for(int i = 0; i < streetLength; i++) { if(street.charAt(i) == 'D') continue; if(street.charAt(i) == 'B') continue; if(street.charAt(i) == 'S') continue; if(i < streetLength-1 && street.charAt(i+1)=='B') continue; if(i < streetLength-2 && street.charAt(i+2)=='B') continue; if(i < streetLength-1 && street.charAt(i+1)=='S') continue; if(i > 0 && street.charAt(i-1)=='S') continue; ans++; } return ans; } }
雑感
charは==で比較できる。
文字列を置換するときはreplaceAllが使える。
他の解答者の答えを見た限り、同じ解き方をしている人がいなかったので自分の解答が間違っているのではないか…?