问题
暴力也是优美的算法,接下里是如何剪枝
鹏伟提出了另外的一种想法,便是扫描出现的ai,这可以采用如下的函数
/**
* Returns the index within this string of the first occurrence of the
* specified substring.
*
* <p>The returned index is the smallest value <i>k</i> for which:
* <blockquote><pre>
* this.startsWith(str, <i>k</i>)
* </pre></blockquote>
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param str the substring to search for.
* @return the index of the first occurrence of the specified substring,
* or {@code -1} if there is no such occurrence.
*/
public int indexOf(String str) {
return indexOf(str, 0);
}
/**
* Returns the index within this string of the first occurrence of the
* specified substring, starting at the specified index.
*
* <p>The returned index is the smallest value <i>k</i> for which:
* <blockquote><pre>
* <i>k</i> >= fromIndex {@code &&} this.startsWith(str, <i>k</i>)
* </pre></blockquote>
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param str the substring to search for.
* @param fromIndex the index from which to start the search.
* @return the index of the first occurrence of the specified substring,
* starting at the specified index,
* or {@code -1} if there is no such occurrence.
*/
public int indexOf(String str, int fromIndex) {
return indexOf(value, 0, value.length,
str.value, 0, str.value.length, fromIndex);
}
上述两个函数采用了String来表示str,我们也可以通过字符数组来执行查询的过程
同样的,indexOf和lastIndexOf是字符串查找中两个非常重要的函数。
Java字符串查找
1.14 字符串查找(3种方法)indexOf(), lastlndexOf(), charAt()
public static void main(String[] args) {
String words = "today,monday,sunday";
System.out.println("原始字符串是'"+words+"'");
System.out.println("indexOf(\"day\")结果:"+words.indexOf("day"));
System.out.println("indexOf(\"day\",5)结果:"+words.indexOf("day",5));
System.out.println("indexOf(\"o\")结果:"+words.indexOf("o"));
System.out.println("indexOf(\"o\",6)结果:"+words.indexOf("o",6));
}
原始字符串是'today,monday,sunday'
indexOf("day")结果:2
indexOf("day",5)结果:9
indexOf("o")结果:1
indexOf("o",6)结果:7
编程
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String numStr = scanner.next();
int querys = scanner.nextInt();
for (int i = 0; i < querys; i++) {
int ai = scanner.nextInt();
System.out.println(new Main().getMethodsCount(numStr, ai));
}
}
private Integer getMethodsCount(String numStr, Integer ai) {
List<String> result = new ArrayList<>();
BigInteger m = new BigInteger("1000000007");
BigInteger x = new BigInteger(String.valueOf(ai));
for (int i = 0; i < numStr.length(); i++) {
for (int j = i + 1; j < numStr.length() + 1; j++) {
String substring = numStr.substring(i, j);
BigInteger bigInteger = new BigInteger(substring);
if (bigInteger.mod(m).equals(x)) {
result.add(substring);
}
}
}
return result.size();
}
}
问题
应该是两层循环,并且使用大整数导致的问题。暂时也没有想到其他更好的方式。
总结
真的是令人痛苦的一天,而且这一天也比较拖延。之前的情形再次出现:
- 上午起床无法快速的开始做事情。(9:30开始)
- 编程序到了12:30,备受打击。
- 晚上吃完饭,去了鹏伟宿舍唠嗑,待到了9点。
总之是挺低效的一条,明天要调整一下。