This theme, regular expression
Ruby
For example, if you put together WWWWBBWBBB in WB, it becomes WBWB, and you can see that it can be made into one color in 3 times.
This kind of string processing is easy to solve using regular expressions.
ruby.rb
s = gets.chomp
s.gsub!(/W+/, "W")
s.gsub!(/B+/, "B")
puts s.size - 1
W + represents one or more consecutive ** W ** characters.
Python
python.py
import re
s = input()
s = re.sub(r'W+', "W", s)
s = re.sub(r'B+', "B", s)
print(len(s) - 1)
If you want to use regular expressions in * Python *, you need ʻimport re`. Perl
perl.pl
chomp (my $s = <STDIN>);
$s =~ s/W+/W/g;
$s =~ s/B+/B/g;
print length($s) - 1, "\n";
Java
java.java
import java.util.*;
class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.next();
        sc.close();
        s = s.replaceAll("W+", "W");
        s = s.replaceAll("B+", "B");
        System.out.println(s.length() - 1);
    }
}
| Ruby | Python | Perl | Java | |
|---|---|---|---|---|
| Code length | 71 Byte | 97 Byte | 87 Byte | 310 Byte | 
| Execution time | 36 ms | 38 ms | 21 ms | 239 ms | 
| memory | 10076 KB | 4468 KB | 640 KB | 35160 KB | 
Referenced site
Recommended Posts