热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

我们如何用下划线Java‽

我目前正在通过以下编程练习进行训练:

我目前正在通过以下编程练习进行训练:"Without repeats"。该声明解释了以下内容:


  

给出一个单词字符串,返回一个包含所有重复单词的字符串
  替换为适当数量的下划线。例如,如果
  给定的String是:在这里开始!去吧!?。

  
  

预期输出将是:____我们去了! __ __

  
  

注意如何忽略标点符号(逗号,句号等)和大小写
  确定是否使用过一个单词,但它们仍然显示
  在最后一个字符串中。

我已经想到了伪代码中的以下内容:

Remove all special characters and get just alphabetic ones
Split words by space
For each word
if word is not in result
add the word into result
else
add underscores as needed
return result

在Java中,我编写了以下代码:

import java.util.*;
public class RepeatDelete
{
public static String withoutRepeats /*??*/(String s)
{
//System.out.println("s: "+s);
List uniques = new ArrayList();
List result = new ArrayList();
String[] words = s.split(" ");
//System.out.println("words: "+Arrays.toString(words));
for(int i = 0,j = 0; i String word = words[i];
String alphabetic = word.replaceAll("[^A-Za-z]","");
//System.out.println("alphabetic: "+alphabetic);
for(; j String unique = uniques.get(j);
if(unique.toLowerCase().equals(alphabetic.toLowerCase())){
result.add("_".repeat(word.length()));
break;
}
}
if(j == uniques.size()){
result.add(word);
uniques.add(alphabetic.toLowerCase());
}
}
System.out.println("uniques: "+Arrays.toString(uniques.toArray()));
return String.join(" ",result.toArray(new String[0]));
}
}

测试用例(从练习中获取):

import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ExampleTest
{
@Test public void FixedTest1()
{
String lyrics="Here here here we go!\n"+
"\n"+
"So they're finally here,performing for you\n"+
"If you know the words,you can join in too\n"+
"Put your hands together,if you want to clap\n"+
"As we take you through this monkey rap!\n"+
"Huh!\n"+
"\n"+
"\n"+
"DK\n"+
"Donkey Kong!\n"+
"\n"+
"\n"+
"He's the leader of the bunch,you know him well\n"+
"He's finally back to kick some tail\n"+
"His coconut gun can fire in spurts\n"+
"If he shoots ya,it's gonna hurt!\n"+
"He's bigger,faster,and stronger too\n"+
"He's the first member of the DK crew!\n"+
"Huh!\n"+
"\n"+
"\n"+
"DK\n"+
"Donkey Kong!\n"+
"DK\n"+
"Donkey Kong is here!\n"+
"\n"+
"\n"+
"This Kong's got style,so listen up dudes\n"+
"She can shrink in size,to suit her mood\n"+
"She's quick and nimble when she needs to be\n"+
"She can float through the air and climb up trees!\n"+
"If you choose her,you'll not choose wrong\n"+
"With a skip and a hop,she's one cool Kong!\n"+
"Huh!\n"+
"\n"+
"\n"+
"DK\n"+
"Donkey Kong!\n"+
"\n"+
"\n"+
"He has no style,he has no grace\n"+
"Th-this Kong has a funny face\n"+
"He can handstand when he needs to\n"+
"And stretch his arms out,just for you\n"+
"Inflate himself just like a balloon\n"+
"This crazy Kong just digs this tune!\n"+
"Huh!\n"+
"\n"+
"\n"+
"DK\n"+
"Donkey Kong!\n"+
"DK\n"+
"Donkey Kong is here!\n"+
"\n"+
"\n"+
"He's back again and about time too\n"+
"And this time he's in the mood\n"+
"He can fly real high with his jetpack on\n"+
"With his pistols out,he's one tough Kong!\n"+
"He'll make you smile when he plays his tune\n"+
"But Kremlings beware 'cause he's after you!\n"+
"Huh!\n"+
"\n"+
"\n"+
"DK\n"+
"Donkey Kong!\n"+
"Huh!\n"+
"\n"+
"\n"+
"Finally,he's here for you\n"+
"It's the last member of the DK crew!\n"+
"This Kong's so strong,it isn't funny\n"+
"Can make a Kremling cry out for mummy\n"+
"Can pick up a boulder with relative ease\n"+
"Makes crushing rocks seem such a breeze\n"+
"He may move slow,he can't jump high\n"+
"But this Kong's one hell of a guy!\n"+
"\n"+
"\n"+
"C'mon Cranky,take it to the fridge!\n"+
"\n"+
"\n"+
"Walnuts,peanuts,pineapple smells\n"+
"Grapes,melons,oranges and coconut shells\n"+
"Aww yeah!\n"+
"Walnuts,oranges and coconut shells\n"+
"Aww yeah!";
String without="Here ____ ____ we go!\n"+
"\n"+
"So they're finally _____ performing for you\n"+
"If ___ know the words,___ can join in too\n"+
"Put your hands together,__ ___ want to clap\n"+
"As __ take ___ through this monkey rap!\n"+
"Huh!\n"+
"\n"+
"\n"+
"DK\n"+
"Donkey Kong!\n"+
"\n"+
"\n"+
"He's ___ leader of ___ bunch,___ ____ him well\n"+
"____ _______ back __ kick some tail\n"+
"His coconut gun ___ fire __ spurts\n"+
"__ he shoots ya,it's gonna hurt!\n"+
"____ bigger,and stronger ___\n"+
"____ ___ first member __ ___ __ crew!\n"+
"____\n"+
"\n"+
"\n"+
"__\n"+
"______ _____\n"+
"__\n"+
"______ ____ is _____\n"+
"\n"+
"\n"+
"____ Kong's got style,__ listen up dudes\n"+
"She ___ shrink __ size,__ suit her mood\n"+
"She's quick ___ nimble when ___ needs __ be\n"+
"___ ___ float _______ ___ air ___ climb __ trees!\n"+
"__ ___ choose ____ you'll not ______ wrong\n"+
"With a skip ___ _ hop,_____ one cool _____\n"+
"____\n"+
"\n"+
"\n"+
"__\n"+
"______ _____\n"+
"\n"+
"\n"+
"__ has no ______ __ ___ __ grace\n"+
"Th-this ____ ___ _ funny face\n"+
"__ ___ handstand ____ __ _____ __\n"+
"___ stretch ___ arms out,just ___ ___\n"+
"Inflate himself ____ like _ balloon\n"+
"____ crazy ____ ____ digs ____ tune!\n"+
"____\n"+
"\n"+
"\n"+
"__\n"+
"______ _____\n"+
"__\n"+
"______ ____ __ _____\n"+
"\n"+
"\n"+
"____ ____ again ___ about time ___\n"+
"___ ____ ____ ____ __ ___ ____\n"+
"__ ___ fly real high ____ ___ jetpack on\n"+
"____ ___ pistols ____ ____ ___ tough _____\n"+
"He'll make ___ smile ____ __ plays ___ ____\n"+
"But Kremlings beware 'cause ____ after ____\n"+
"____\n"+
"\n"+
"\n"+
"__\n"+
"______ _____\n"+
"____\n"+
"\n"+
"\n"+
"________ ____ ____ ___ ___\n"+
"____ ___ last ______ __ ___ __ _____\n"+
"____ ______ __ strong,it isn't _____\n"+
"___ ____ _ Kremling cry ___ ___ mummy\n"+
"___ pick __ _ boulder ____ relative ease\n"+
"Makes crushing rocks seem such _ breeze\n"+
"__ may move slow,__ can't jump ____\n"+
"___ ____ ______ ___ ____ __ _ guy!\n"+
"\n"+
"\n"+
"C'mon Cranky,____ __ __ ___ fridge!\n"+
"\n"+
"\n"+
"Walnuts,oranges ___ _______ shells\n"+
"Aww yeah!\n"+
"________ ________ _________ ______\n"+
"_______ _______ _______ ___ _______ ______\n"+
"___ _____";
assertEquals(without,RepeatDelete.withoutRepeats(lyrics));
}

我们看到测试期望:

expected:<...
So they're finally [_____ performing for you
If ___ know the words,___ can join in too
Put your hands together,__ ___ want to clap
As __ take ___ through this monkey rap!
Huh!
DK
Donkey Kong!
He's ___ leader of ___ bunch,___ ____ him well
____ _______ back __ kick some tail
His coconut gun ___ fire __ spurts
__ he shoots ya,it's gonna hurt!
____ bigger,and stronger ___
____ ___ first member __ ___ __ crew!
____
__
______ _____
__
______ ____ is _____
____ Kong's got style,__ listen up dudes
She ___ shrink __ size,__ suit her mood
She's quick ___ nimble when ___ needs __ be
___ ___ float _______ ___ air ___ climb __ trees!
__ ___ choose ____ you'll not ______ wrong
With a skip ___ _ hop,_____ one cool _____
____
__
______ _____
__ has no ______ __ ___ __ grace
Th-this ____ ___ _ funny face
__ ___ handstand ____ __ _____ __
___ stretch ___ arms out,just ___ ___
Inflate himself ____ like _ balloon
____ crazy ____ ____ digs ____ tune!
____
__
______ _____
__
______ ____ __ _____
____ ____ again ___ about time ___
___ ____ ____ ____ __ ___ ____
__ ___ fly real high ____ ___ jetpack on
____ ___ pistols ____ ____ ___ tough _____
He'll make ___ smile ____ __ plays ___ ____
But Kremlings beware 'cause ____ after ____
____
__
______ _____
____
________ ____ ____ ___ ___
____ ___ last ______ __ ___ __ _____
____ ______ __ strong,it isn't _____
___ ____ _ Kremling cry ___ ___ mummy
___ pick __ _ boulder ____ relative ease
Makes crushing rocks seem such _ breeze
__ may move slow,__ can't jump ____
___ ____ ______ ___ ____ __ _ guy!
C'mon Cranky,____ __ __ ___ fridge!
Walnuts,pineapple smells
Grapes,oranges ___ _______ shells
Aww yeah!
________ ________ _________ ______
_______ _______ _______ ___ _______ ______
___ _____]>

但是,代码输出:

but was:<...
So they're finally [here,performing for you
If you know the words,you can join in too
Put your hands together,if you want to clap
As we take you through this monkey rap!
Huh!
DK
Donkey Kong!
He's the leader of the bunch,you know him well
He's finally back to kick some tail
His coconut gun can fire in spurts
If he shoots ya,it's gonna hurt!
He's bigger,and stronger too
He's the first member of the DK crew!
Huh!
DK
Donkey Kong!
DK
Donkey Kong is here!
This Kong's got style,so listen up dudes
She can shrink in size,to suit her mood
She's quick and nimble when she needs to be
She can float through the air and climb up trees!
If you choose her,you'll not choose wrong
With a skip and a hop,she's one cool Kong!
Huh!
DK
Donkey Kong!
He has no style,he has no grace
Th-this Kong has a funny face
He can handstand when he needs to
And stretch his arms out,just for you
Inflate himself just like a balloon
This crazy Kong just digs this tune!
Huh!
DK
Donkey Kong!
DK
Donkey Kong is here!
He's back again and about time too
And this time he's in the mood
He can fly real high with his jetpack on
With his pistols out,he's one tough Kong!
He'll make you smile when he plays his tune
But Kremlings beware 'cause he's after you!
Huh!
DK
Donkey Kong!
Huh!
Finally,he's here for you
It's the last member of the DK crew!
This Kong's so strong,it isn't funny
Can make a Kremling cry out for mummy
Can pick up a boulder with relative ease
Makes crushing rocks seem such a breeze
He may move slow,he can't jump high
But this Kong's one hell of a guy!
C'mon Cranky,take it to the fridge!
Walnuts,oranges and coconut shells
Aww yeah!
Walnuts,oranges and coconut shells
Aww yeah!]>

我知道代码会在结果中插入一个重复的“此处”,但是为什么呢?

您会注意到,“此处”已添加到唯一标识中,因此不应将其添加到结果中!

能帮我吗?

我也读过:


  • Remove Duplicate Lines from Text using Java

  • Removing duplicates from a String in Java

  • Finding repeated words on a string and counting the repetitions

  • Get unique values from arraylist in java

您将如何调试此代码,甚至提出更简单的方法?

我们怎么用下划线Java替换重复的单词?

编辑:在尝试理解@kevin ternet答案并且不复制它之后,我进行了编码:

import java.util.*;
public class RepeatDelete
{
public static String withoutRepeats(String s)
{
String[] words = s.split(" ");
List result = new ArrayList(Arrays.asList(words));
return String.join(" ",replaceRepeatedWords(result,0));
}
public static List replaceRepeatedWords(List result,int i){
String originalWord = result.get(i);
Collections.replaceAll(result,result.get(i),"_".repeat(result.get(i).length()));
result.set(i,originalWord);
if(i == result.size() - 1){
return result;
}
return replaceRepeatedWords(result,i+1);
}
}

不是用下划线替换所有重复的单词,而是替换了最后一个。

给出:

“我们在这里开始!\ n”

它输出:

在这里____我们去!

代替:

我们在这里____ ____!


在不运行代码的情况下,我看不到任何明显的地方,但是我建议您以一种更简单的方式编写它,以便于调试:

JDK提供了一些使您的生活更轻松的类,例如,将唯一词列表更好地实现为Set,那么您就不需要第二个嵌套循环了,因为您可以简单地询问它if (uniques.contains(alphabetic))。 (作为奖励,以这种方式进行测试可以提供更好的性能,尽管性能现在不应该成为您的关注点)。您还可以使用for-each循环而不是使用数字索引:

for (String word : words.split(" ") {
String alphabetic = word.replaceAll("...");
// ...
}

大多数人会同意,这对于人类来说“读起来”更好,可读代码更易于调试和使用。

我还建议使用StringBuilder来构建输出字符串,而不是另一个列表。这几乎就是它设计的用例。

StringBuilder output = new StringBuilder();
output.append(word);
// etc...
System.out.println(output.toString());

祝您好运,我认为您有正确的方法,但是有更清洁(更简单)的方法来实现它。确保使用允许您设置断点并逐行逐步运行代码的IDE。

,

或者在此基础上,使用Stream和更简单的递归来缩短:

public static void main(String[] args) {
String lyrics="Here here here we go!\n";
String[] tableau = lyrics.split(" ");
List liste = Arrays.stream(tableau).map(String::toLowerCase).collect(Collectors.toList());
System.out.println(liste);
play(liste,0);
System.out.println(liste);
}
public static void play (List phrase,int i) {
if (i String mot = phrase.get(i);
String repeat = mot.replaceAll("[a-z]","_");
Collections.replaceAll(phrase,mot,repeat);
phrase.set(i,mot);
play(phrase,i+1);
}
}

输出:

[这里,这里,这里,我们,去!
]

[这里,____,____,我们,走!
]


推荐阅读
  • 1.如何在运行状态查看源代码?查看函数的源代码,我们通常会使用IDE来完成。比如在PyCharm中,你可以Ctrl+鼠标点击进入函数的源代码。那如果没有IDE呢?当我们想使用一个函 ... [详细]
  • Explore how Matterverse is redefining the metaverse experience, creating immersive and meaningful virtual environments that foster genuine connections and economic opportunities. ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • 本文将介绍如何编写一些有趣的VBScript脚本,这些脚本可以在朋友之间进行无害的恶作剧。通过简单的代码示例,帮助您了解VBScript的基本语法和功能。 ... [详细]
  • 技术分享:从动态网站提取站点密钥的解决方案
    本文探讨了如何从动态网站中提取站点密钥,特别是针对验证码(reCAPTCHA)的处理方法。通过结合Selenium和requests库,提供了详细的代码示例和优化建议。 ... [详细]
  • 本文详细介绍了如何在Linux系统上安装和配置Smokeping,以实现对网络链路质量的实时监控。通过详细的步骤和必要的依赖包安装,确保用户能够顺利完成部署并优化其网络性能监控。 ... [详细]
  • 本文详细解析了Python中的os和sys模块,介绍了它们的功能、常用方法及其在实际编程中的应用。 ... [详细]
  • 并发编程:深入理解设计原理与优化
    本文探讨了并发编程中的关键设计原则,特别是Java内存模型(JMM)的happens-before规则及其对多线程编程的影响。文章详细介绍了DCL双重检查锁定模式的问题及解决方案,并总结了不同处理器和内存模型之间的关系,旨在为程序员提供更深入的理解和最佳实践。 ... [详细]
  • Docker的安全基准
    nsitionalENhttp:www.w3.orgTRxhtml1DTDxhtml1-transitional.dtd ... [详细]
  • 本文介绍如何在 Android 中通过代码模拟用户的点击和滑动操作,包括参数说明、事件生成及处理逻辑。详细解析了视图(View)对象、坐标偏移量以及不同类型的滑动方式。 ... [详细]
  • 深入理解 SQL 视图、存储过程与事务
    本文详细介绍了SQL中的视图、存储过程和事务的概念及应用。视图为用户提供了一种灵活的数据查询方式,存储过程则封装了复杂的SQL逻辑,而事务确保了数据库操作的完整性和一致性。 ... [详细]
  • ImmutableX Poised to Pioneer Web3 Gaming Revolution
    ImmutableX is set to spearhead the evolution of Web3 gaming, with its innovative technologies and strategic partnerships driving significant advancements in the industry. ... [详细]
  • 本文介绍如何使用Python进行文本处理,包括分词和生成词云图。通过整合多个文本文件、去除停用词并生成词云图,展示文本数据的可视化分析方法。 ... [详细]
  • MySQL索引详解与优化
    本文深入探讨了MySQL中的索引机制,包括索引的基本概念、优势与劣势、分类及其实现原理,并详细介绍了索引的使用场景和优化技巧。通过具体示例,帮助读者更好地理解和应用索引以提升数据库性能。 ... [详细]
author-avatar
董雪高
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有