如何在java中返回字符串中最长的字符序列?

问题描述 投票:0回答:7

以下是我最终所做的,但我没有找到正确的答案。

示例 - 如果我有序列“hellloo”,则输出将为“lll”。请告诉我出了什么问题?

public class LongestSequenceOfChar {
    static String testcase1="hellloo";

    public static void main(String[] args) {
        LongestSequenceOfChar test = new LongestSequenceOfChar();
        String result = test.longestSequenceOfChar(testcase1);
        System.out.println(result);
    }
    public String longestSequenceOfChar(String str){
        String result="";
        for(int i=0;i<str.length();i++){
            char ch=str.charAt(i);
            for(int j=i+1;j<str.length();j++){
                char ch1=str.charAt(j);
                if(ch!=ch1){
                    continue;
                }
                result+=ch;
            }
        }
        return result;
    }
}
java
7个回答
5
投票

您现在应该有一个计数器来计算最长序列的数量。当您发现更长的序列时,您应该重置

result
并相应地更新计数器。

但是,你可以有更好的解决方案:

  • 有一个大小为 26 的数组(英文字母的大小)。现在,您迭代字符串,并为其中的每个
    char
    ,在辅助数组的相应单元格中添加 1。
  • 使用
    HashMap
    ,其中
    char
    作为 key,其显示的数字作为 value。如果它是一个新的
    char
    ,您只需将其设置为 0 值,如果存在,则增加现有的
  • 提示:使用调试器,它可以救你的命。


5
投票


2
投票

public String longestSequenceOfChar(String str){ String interimresult=""; String result=""; //final result for(int i=0;i<str.length();i++){ char ch=str.charAt(i); interimresult += ch; //add the letter once for(int j=i+1;j<str.length();j++){ char ch1=str.charAt(j); if(ch!=ch1){ break; } interimresult +=ch; } if(interimresult.length()>result.length())//store the result if it is longer result = interimresult; interimresult = ""; //clear to continue with the next letter } return result; }



2
投票

public String longestSequenceOfChar(String str) { String result = ""; for (int i = 0; i < str.length(); i++) { int j = i; while(j < str.length() && str.charAt(j) == str.charAt(i)) { j++; } // If this one is longer than previous, then asign it to result. if(j - i > result.length()) { result = str.substring(i, j); } } return result; }



1
投票

import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public class MaximumOccuringCharUsingHashMap { public static void main(String[] args) { String test = "test samples"; MaximumOccuringCharUsingHashMap mc = new MaximumOccuringCharUsingHashMap(); System.out.println( mc.findMaximunOccurenceCharacter(test)); } char findMaximunOccurenceCharacter(String input){ Map<Character, Integer> countHash = new HashMap<Character, Integer>(); for(int i=0; i<input.length() ;i++ ){ char currentChar = input.charAt(i); if(countHash.get(currentChar)==null){ countHash.put(currentChar, 1); }else{ countHash. put(currentChar, countHash.get(currentChar)+1); } } int max = Collections.max(countHash.values()); char maxCharacter =0; for(Entry<Character, Integer> entry :countHash.entrySet()){ if(entry.getValue() == max){ maxCharacter = entry.getKey(); } } return maxCharacter; } }

上面的代码将打印 s 作为输出,它在给定字符串中出现的最大次数。


0
投票

public class HelloWorld { public static void main(String[] args) { System.out.println(maxLen(null)); System.out.println(maxLen("")); System.out.println(maxLen("a")); System.out.println(maxLen("aa")); System.out.println(maxLen("abcddd")); System.out.println(maxLen("abcd")); System.out.println(maxLen("aabbba")); } public static String maxLen(String input) { // Avoid NPEs if (input == null) { return null; } int maxLen = 0; int tempLen = 0; char prevChar = 0; char c = 0; char repeatChar = 0; for (int i = 0; i < input.length(); i++) { c = input.charAt(i); if (c == prevChar) { tempLen++; if (tempLen > maxLen) repeatChar = c; } else { maxLen = (tempLen > maxLen) ? tempLen : maxLen; prevChar = c; tempLen = 1; } } maxLen = (tempLen > maxLen) ? tempLen : maxLen; if (maxLen == 0 || maxLen == 1) return "no sequence found"; else { String str = ""; for (int i = 1; i <= maxLen; i++) str += String.valueOf(repeatChar); return str; } } }

这将通过所有测试用例。


0
投票

public class mostCommonChar { /** * @throws IllegalArgumentException Character length must be at least 2 * @return String * @param word A string of characters * @apiNote Returns the longest sequence of character in a given word or text * */ public static String getMostCommonChar(String word) { int occurrence = 0; String mostCommonChar = ""; String[] characters = {}; HashMap<String, Integer> characterList = new HashMap<String, Integer>(); if(word.length() < 2) { throw new IllegalArgumentException(); } characters = word.trim().split(""); for(String character : characters) { if(characterList.containsKey(character)) { occurrence++; mostCommonChar = character; } else { characterList.put(character, 1); } } return occurrence == 0 ? "None" : mostCommonChar; } } // input = hellloo, output = l // input = abcd, output = None // input = x, output = IllegalArgumentException

	
© www.soinside.com 2019 - 2024. All rights reserved.