编写一个程序,打印s的最长子字符串,其中字母按字母顺序出现

如何解决编写一个程序,打印s的最长子字符串,其中字母按字母顺序出现

我正在使用Java在线学习编程。我知道表达式,变量,if语句,迭代,静态方法,数组,开关和其他基本内容。我目前正在努力处理涉及编写方法的作业,如果我能得到一些帮助,那将是很好的。

这里是:

问题:假设s是一串小写字符。编写一个程序,打印s的最长子串,其中字母按字母顺序出现。例如,如果s ='azcbobobegghakl',则您的程序应打印

Longest substring in alphabetical order is: beggh

在某些情况下,请打印第一个子字符串。例如,如果s ='abcbcd',则您的程序应打印

Longest substring in alphabetical order is: abc

这是我到目前为止所拥有的:

  • 将String的字母作为单个字母放入数组中
  • for循环按字母顺序搜索数组中最长的子字符串
static String problemThree(String s){
        for(int i = 0; i < s.length(); i++){
            
        }
        return s;
    }

我不确定下一步该怎么办或从哪里开始这个问题。

解决方法

对于问题2,您可以从字符串的开头开始循环,并以substring = 3 char of string例如。 azc,zcb直到list [length-3](3 =“ bob”的长度),并且永远是substring.equals(“ bob”)计数++。

对于问题3,使用占位符String longestString =“”。 对字符串中的每个字母运行一个for循环,定义currentString =“”,从当前索引开始运行另一个for循环,如果按字母顺序将字母追加到currentString(查找String.compareTo()),一旦找到一个字母不是按字母顺序排列,请检查currentString是否长于longestString-> longestString = currentString。

,

我想知道问题1在哪里。

问题2 : 这是switch的完全错误用法。您正在做的是将字符串s"bob"进行比较,看它们是否相等。您错误方法的另一种选择是

if ("bob".equals(s)) answer++;

更多情况下,您正在检查s之间的相等性的字符串越多。

正确的方法是利用String.indexOf(String,int)方法,该方法从指定的索引处开始,返回给定字符串在原始字符串(如果存在)中的索引。

例如,

  1. "abcbobabc".indexOf("bob",0)返回3。
  2. "abcbobabc".indexOf("bob",3)返回3。
  3. "abcbobabc".indexOf("bob",5)返回-1。 (找不到)

提醒:第一个索引为0。

找到第一个外观后,从下一个索引开始搜索,因此“第一个外观”将是下一个(如果存在)而不是我们找到的下一个。

  1. "bobob".indexOf("bob",0)返回0。
  2. "bobob".indexOf("bob",1)返回2。
  3. "bobob".indexOf("bob",3)返回-1。

但是我们只想计数外观,而不要返回外观索引。因此,这是代码:

if (s == null) return; // prevent NullPointerException
int i = 0;
int count = 0;
while ((i = s.indexOf("bob",i)) != -1) {
    i++;
    count++;
}
return count;

问题3 :Java没有一种方法可以按字母顺序直接扫描子字符串,因此您需要自己通过逐字符扫描来实现它。

首先,仅当两个字符的大写或小写在一起时,才能将两个字符的字母顺序进行比较。

String longest = "";
StringBuilder builder = new StringBuilder();
// for storing character streak in alphabetical order

for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i); // Access the character at index i in the string given.
    int length = builder.length();
    if (length == 0 /* no streak */ 
        || Character.toLowerCase(builder.charAt(length - 1)) <= Character.toLowerCase(c)
        /* has streak,and the new character has alphabetical order greater than 
the last one e.g. z greater than a */) {
        /* starts or continues the streak */
        builder.append(c);
    } else {
        /* stops the streak */
        if (length > longest.length()) {
            /* new streak is higher than the last one,so replace it */
            longest = builder.toString();
        }
        /* either streak is not high enough or not,resets the streak */
        builder = new StringBuilder();
    }
}
return longest;

基本上整个代码都是

  1. 遍历所有字符
  2. 继续将按字母顺序排列的字符添加到字符串生成器
  3. 如果下一个字符没有遵循顺序,请停止连胜
  4. 查看构建器构建的字符串是否长于最后一个字符串
,

对于问题2,我个人将保存一个索引i并增加s.length()次,在i处增加子字符串,检查子字符串是否以“ bob”开头。

对于问题3,保存索引i并增加s.length()次,在i处子字符串,保存索引j并增加substring.length()次,最后保存一个字符,将substring.charAt(j)与最后一个字符,如果它出现在字母表中的位置比最后一个字符晚,或者它们相同,则将字符追加到构建的String中并更新最后一个字符,最后,如果built.length()> longest.length()将最长更新为Built

    private static int problemTwo() {
        String s = "azcbobobegghakl";
        int count = 0;

        for (int i = 0; i < s.length(); i++) {
            if (s.substring(i).startsWith("bob")) {
                count++;
            }
        }

        return count;
    }

    private static String problemThree() {
        String s = "azcbobobegghakl",longest = "";

        // Increment i s.length() times,i determining how far into the string we start at e.g. if i is 5 substring will be "bobegghakl"
        for (int i = 0; i < s.length(); i++) {
            String substring = s.substring(i),built = "";
            char last = 0;

            // Increment j substring.length() times
            for (int j = 0; j < substring.length(); j++) {
                char c = substring.charAt(j);

                // If the last character occurs earlier in the alphabet or the same as the current character,append it to the built string,and update the last character to be the current
                if (last <= c) {
                    built = built.concat(Character.toString(c));
                    last = c;
                } else {
                    // Break out of the for loop if the current character occurs earlier in the alphabet than the last
                    break;
                }
            }
            
            if (built.length() > longest.length()) {
                longest = built;
            }
        }

        return longest;
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-