数组中两个字符串的最小距离
1.题目:
2.解析:
这里利用预处理思想:要找多个位置先记录下某个位置:
这里 i 遍历来记录s1,和s2的位置,不断更新来找到最小距离。
代码:
代码语言:javascript代码运行次数:0运行复制public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
String[] str = reader.readLine().split(" ");
String s1 = str[0],s2 = str[1];
int prev1 = -1;//记录s1位置
int prev2 = -1;//记录s2位置
int ret = Integer.MAX_VALUE;
for(int i = 0; i < n; i++) {
if(str[i].equals(s1)){ //前面找s2
if(prev2 != -1){
//看左边是否有s2
ret = Math.min(ret,i-prev2);
prev1 = i;
}
}
if(str[i].equals(s2)){ //前面找s1
if(prev1 != -1){
//看左边是否有s1
ret = Math.min(ret,i-prev1);
prev2 = i;
}
}
}
System.out.println(ret == Integer.MAX_VALUE ? -1 : ret);
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2024-09-29,如有侵权请联系 cloudcommunity@tencent 删除数组字符串intstring遍历发布者:admin,转转请注明出处:http://www.yc00.com/web/1754959091a5221751.html
评论列表(0条)