Title description
Description: Give you a pure numeric string s, please return the number of consecutive single numeric substrings
prompt:
1 <= s.length <= 100
Enter a description:
“11121”
Explanation:
The substrings containing only a single letter are: "111", "11", "1" and "2"
"111" appears 1 time
"11" appears 2 times
"1" appears 4 times
"2" appears 1 time
Total 1 + 2 + 4 + 1 = 8
Problem-solving ideas:
- Find all substrings first
- Then judge whether the substrings are all the same characters
/**
* 暴力法
* @param str
* @return
*/
public static int test_1(String str) {
int res = 0;
HashMap<String,Integer> map = new HashMap<>();
for(int i = 0; i < str.length(); i++){
for (int j = i+1; j<=str.length(); j++){
map.put(str.substring(i,j),map.getOrDefault(str.substring(i,j),0)+ 1);
}
}
System.out.println(map.toString());
//遍历map的所有key
for (String key:map.keySet()){
//System.out.println("key= "+key+" and value= "+map.get(key));
//判断key中的字符是否都是相同字符
if (isSameChars(key)){
System.out.println("key= "+key+" and value= "+map.get(key));
res = res +map.get(key);
}
}
return res;
}
public static boolean isSameChars (String str) throws IllegalArgumentException {
if (str == null)
throw new IllegalArgumentException("Input string should not be null.");
else if (str.length() < 2)
return true;
char first = str.charAt(0);
for (int i=1; i<str.length(); i++)
if (str.charAt(i) != first)
return false;
return true;
}