编写Java程序:仅用String的charAt和length函数找出现超3次的字符
Got it, let's work through this problem step by step. The goal is to identify characters in a string that appear more than 3 times, and we're restricted to using only charAt() and length() from the String class—no toCharArray() or HashMap allowed, unlike the reference code provided.
Approach
Since we can't use HashMap to track frequencies directly, we'll use a straightforward nested loop approach with a boolean array to avoid reprocessing the same character:
- First, iterate over each character in the string using
charAt(). - For each character, if we haven't checked it before, count its total occurrences by scanning the entire string again with
charAt(). - If the count exceeds 3, output the character, then mark it as checked so we don't process it again (this prevents duplicate outputs of the same character).
Code Implementation
public class StringExample { public static void main(String args[]) { String str = "sofiiiffjjjh"; // Handle null input to avoid exceptions if (str == null) { return; } // Boolean array to track checked characters (covers standard ASCII range) boolean[] checkedChars = new boolean[256]; for (int i = 0; i < str.length(); i++) { char currentChar = str.charAt(i); // Skip if we've already counted this character if (checkedChars[currentChar]) { continue; } int count = 0; // Count how many times currentChar appears in the string for (int j = 0; j < str.length(); j++) { if (str.charAt(j) == currentChar) { count++; } } // Print the character if it occurs more than 3 times if (count > 3) { System.out.println(currentChar); } // Mark the character as checked to avoid reprocessing checkedChars[currentChar] = true; } } }
Explanation
- Null Handling: We first check if the input string is null to avoid
NullPointerExceptionwhen callinglength()orcharAt(). - Checked Characters Tracking: The
checkedCharsarray uses the ASCII value of each character as an index. Once we process a character, we set its corresponding index totrueso we don't waste time counting it again. - Frequency Count: For each unchecked character, we loop through the entire string with
charAt()to tally its occurrences. If the count is greater than 3, we print the character.
This solution strictly follows the constraints—only using charAt() and length()—and achieves the same result as the original HashMap-based code, without relying on additional data structures or helper methods.
内容的提问来源于stack exchange,提问作者Mouneshwar Iranna

