AtCoder Beginner Contest 107 B - Grid Compression Difficulty: 434
Ce thème, opération de chaîne de caractères Ruby
ruby.rb
h, w = gets.split.map(&:to_i)
a = []
h.times do |i|
s = gets.chomp
a.push(s) if s.index('#')
end
(w - 1).downto(0) do |i|
if a.all?{|x| x[i] == '.'}
a.each do |x|
x[i] = ''
end
end
end
puts a
count.rb
a.push(s) if s.count('.') != w
a.push(s) if s.index('#')
a.push(s) if s.contain?('#')
La méthode count, la méthode ʻindex, la méthode contain` et d'autres expressions régulières sont également OK.
index.rb
x[i] = ''
Pour * Ruby *, vous pouvez remplacer directement les caractères spécifiés dans l'index. ** Addenda ** J'ai examiné le code à partir des commentaires que j'ai reçus. Python
python.py
h, w = map(int, input().split())
a = []
for i in range(h):
s = input()
if s.count('.') != w:
a.append(s)
b = []
for i in range(w):
f = True
for x in a:
if x[i] != '.':
f = False
if f:
b.append(i)
for x in a:
for i in range(len(x)):
f = True
for j in b:
if i == j:
f = False
if f:
print(x[i], end='')
print()
find.py
if s.count('.') != w:
if s.find('#') == -1:
Vous pouvez également utiliser la méthode find.
perl.pl
chomp (my ($h, $w) = split / /, <STDIN>);
my @a;
for my $i (1..$h) {
chomp (my $s = <STDIN>);
if (scalar(grep {$_ eq '.'} (split '', $s)) != $w) {
push @a, $s;
}
}
for my $i (1..$w) {
my $f = 1;
for my $x (@a) {
$f = 0 if substr($x, $w - $i, 1) ne '.';
}
if ($f) {
for my $x (@a) {
substr($x, $w - $i, 1) = '';
}
}
}
for my $x (@a) {
print "$x\n";
}
grep.pl
if (scalar(grep {$_ eq '.'} (split '', $s)) != $w) {
if (index($s, '#') == -1) {
ʻIndex` est également OK. Java
java.java
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int h = Integer.parseInt(sc.next());
int w = Integer.parseInt(sc.next());
List<String> a = new ArrayList<>();
for (int i = 0; i < h; i++) {
String s = sc.next();
if (s.contains("#")) {
a.add(s);
}
}
sc.close();
List<Integer> b = new ArrayList<>();
for (int i = 0; i < w; i++) {
boolean f = false;
for (String x : a) {
if (x.charAt(i) == '#') {
f = true;
break;
}
}
if (f) {
b.add(i);
}
}
for (String x : a) {
for (int i = 0; i < w; i++) {
if (b.contains(i))
System.out.print(x.charAt(i));
}
System.out.println();
}
}
}
contains.java
if (s.contains("#")) {
Il ne semble pas y avoir de moyen facile de compter le nombre de ., donc j'utilise la méthode contains.
** Addenda **
Dans la section des commentaires, j'ai eu l'idée de «diviser» avec «.».
De plus, j'ai reçu un commentaire disant que «charAt» est meilleur que «substring», j'ai donc modifié le code.
| Ruby | Python | Perl | Java | |
|---|---|---|---|---|
| Longueur du code | 226 Byte | 457 Byte | 410 Byte | 1042 Byte |
| Temps d'exécution | 9 ms | 35 ms | 5 ms | 219 ms |
| Mémoire | 1788 KB | 4468 KB | 512 KB | 25032 KB |
Recommended Posts