Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用地图上的缩写缩短句子_Java_Algorithm_Dictionary_Recursion_Mapping - Fatal编程技术网

Java 使用地图上的缩写缩短句子

Java 使用地图上的缩写缩短句子,java,algorithm,dictionary,recursion,mapping,Java,Algorithm,Dictionary,Recursion,Mapping,提示: 给出一个句子和一组已知的缩写,找出一种有效的方法来缩短句子 这是我解决这个问题的代码。然而,在我的最终答案中,我只能得到一个缩写 import java.util.*; class Solution{ public static void main(String[] args) { Map<String, String> dict = new HashMap<>(); dict.put("be right back", "B

提示: 给出一个句子和一组已知的缩写,找出一种有效的方法来缩短句子

这是我解决这个问题的代码。然而,在我的最终答案中,我只能得到一个缩写

import java.util.*;
class Solution{
    public static void main(String[] args) {
        Map<String, String> dict = new HashMap<>();
        dict.put("be right back", "BRB");
        dict.put("be right there", "BRT");
        dict.put("be right later", "BRL");
        dict.put("be", "B");
        dict.put("later", "L8R");

        String s = "I will be right there later";
        System.out.println(convert(s, dict));
    }

    public static String convert(String s, Map<String, String> dict) {
        String[] words = s.split(" ");
        List<String> converted = new ArrayList<>();

        List<String> toCheck = new ArrayList<>();
        for (int i = 0; i < words.length; i++){
            for (int j = i; j < words.length; j++){
                String[] substring = Arrays.copyOfRange(words, i, j+1);
                String combined = "";
                for (String str : substring){
                    combined += str + " ";
                }
                combined = combined.strip();
                toCheck.add(combined);
            }
        }

        String ans = "";
        String target = "";
        for (String str : toCheck){
            if (dict.containsKey(str)){
                int index = s.indexOf(str);
                ans = s.substring(0, index) + dict.get(str) + s.substring(index + str.length());
            }
        }

        return ans;

    }

}
import java.util.*;
类解决方案{
公共静态void main(字符串[]args){
Map dict=newhashmap();
dict.put(“马上回来”,“BRB”);
dict.put(“就在那里”、“快速公交”);
dict.put(“稍后再做”,“BRL”);
dict.put(“be”,“B”);
dict.put(“后来的”、“L8R”);
String s=“我一会儿就到”;
System.out.println(convert(s,dict));
}
公共静态字符串转换(字符串s,映射dict){
字符串[]字=s.split(“”);
列表转换=新的ArrayList();
List-toCheck=new-ArrayList();
for(int i=0;i

我认为有一种递归方式来执行转换,但我不太确定如何执行。有人能帮我解决这个问题吗?或者,能告诉我类似的问题吗?提前谢谢

你的问题就在这里:你只是在检查最后一个答案。请参阅下面我嵌入的评论


        for (String str : toCheck){
         if (dict.containsKey(str)){
                s = s.replace(str, dict.get(str));
                System.out.println(s);
          }
        }

        return s;
这一行实际上保持了字符串的完整性,除了替换部分。因此,只有映射中最后匹配的字符串存储在
ans

您的代码也不会处理重叠的情况,例如,
现在更快
我现在会更快
。在这种情况下,您可能需要匹配
I将更快
以获得正确的缩写

下面是我如何解决它的。您可以使用正则表达式,但在足够长的字符串上,正则表达式的速度似乎较慢,因为在匹配之前先编译正则表达式

片段:

import java.util.*;
class Solution{
    public static void main(String[] args) {
        Map<String, String> dict = new HashMap<>();
        dict.put("be right back", "BRB");
        dict.put("be right there", "BRT");
        dict.put("be right later", "BRL");
        dict.put("be", "B");
        dict.put("be back soon","B back soon");
        dict.put("faster than light","FTL");
        dict.put("later", "L8R");

        String[] tests = {
            "I will be right there later",
            "I will be right there",
            "I will be there",
            "I will go right there",
            "I will be there later",
            "I am faster than you",
            "Never faster than light",
            "Faster than light today"
        };

        for(String test_case : tests){
            System.out.println(test_case + " => " + convert(test_case, dict));   
        }
    }

    public static String convert(String s, Map<String, String> dict) {

        List<String> dict_words = new ArrayList<>(dict.keySet());
        Map<Integer,String[]> replacement_index = new HashMap<>();

        Collections.sort(dict_words,new Comparator<String>(){
            public int compare(String s1,String s2){
                if(s1.length() == s2.length()) return 0; // order doesn't seem to matter for same length strings
                return s2.length() - s1.length(); // return bigger length string first
            }
        });

        String temp = s.toLowerCase(); // to perform case insensitive match
        for(String dict_str : dict_words){
            String dict_str_lower = dict_str.toLowerCase(); // to perform case insensitive match
            int index = 0;
            do{
                index = temp.indexOf(dict_str_lower,index);
                if(index != -1){
                    replacement_index.putIfAbsent(index,new String[]{dict.get(dict_str),dict_str});
                    index++;// to get the next match index of the same word in the string.
                }
            }while(index != -1 && index < temp.length());
        }

        StringBuilder res = new StringBuilder("");

        for(int i = 0;i < s.length(); ++i){
            if(replacement_index.containsKey(i)){
                res.append(replacement_index.get(i)[0]);
                i += replacement_index.get(i)[1].length() - 1;
            }else{
                res.append(s.charAt(i));
            }
        }

        return res.toString();
    }

}
import java.util.*;
类解决方案{
公共静态void main(字符串[]args){
Map dict=newhashmap();
dict.put(“马上回来”,“BRB”);
dict.put(“就在那里”、“快速公交”);
dict.put(“稍后再做”,“BRL”);
dict.put(“be”,“B”);
dict.put(“很快回来”、“很快回来”);
dict.put(“超光速”、“超光速”);
dict.put(“后来的”、“L8R”);
字符串[]测试={
“我一会儿就到”,
“我马上就到”,
“我会在那里”,
“我就去那儿”,
“我稍后会到”,
“我比你快”,
“永不超过光速”,
“今天比光还快”
};
用于(字符串测试\案例:测试){
System.out.println(测试用例+“=>”+转换(测试用例,dict));
}
}
公共静态字符串转换(字符串s,映射dict){
List dict_words=new ArrayList(dict.keySet());
Map replacement_index=new HashMap();
Collections.sort(dict_单词,新比较器(){
公共整数比较(字符串s1、字符串s2){
如果(s1.length()==s2.length())返回0;//对于相同长度的字符串,顺序似乎并不重要
返回s2.length()-s1.length();//首先返回长度较大的字符串
}
});
字符串temp=s.toLowerCase();//执行不区分大小写的匹配
for(字符串dict_str:dict_单词){
String dict_str_lower=dict_str.toLowerCase();//执行不区分大小写的匹配
int指数=0;
做{
指数=温度指数(指数较低);
如果(索引!=-1){
替换_index.putIfAbsent(索引,新字符串[]{dict.get(dict_str),dict_str});
index++;//获取字符串中同一单词的下一个匹配索引。
}
}而(索引!=-1&&index
演示:

算法:

import java.util.*;
class Solution{
    public static void main(String[] args) {
        Map<String, String> dict = new HashMap<>();
        dict.put("be right back", "BRB");
        dict.put("be right there", "BRT");
        dict.put("be right later", "BRL");
        dict.put("be", "B");
        dict.put("be back soon","B back soon");
        dict.put("faster than light","FTL");
        dict.put("later", "L8R");

        String[] tests = {
            "I will be right there later",
            "I will be right there",
            "I will be there",
            "I will go right there",
            "I will be there later",
            "I am faster than you",
            "Never faster than light",
            "Faster than light today"
        };

        for(String test_case : tests){
            System.out.println(test_case + " => " + convert(test_case, dict));   
        }
    }

    public static String convert(String s, Map<String, String> dict) {

        List<String> dict_words = new ArrayList<>(dict.keySet());
        Map<Integer,String[]> replacement_index = new HashMap<>();

        Collections.sort(dict_words,new Comparator<String>(){
            public int compare(String s1,String s2){
                if(s1.length() == s2.length()) return 0; // order doesn't seem to matter for same length strings
                return s2.length() - s1.length(); // return bigger length string first
            }
        });

        String temp = s.toLowerCase(); // to perform case insensitive match
        for(String dict_str : dict_words){
            String dict_str_lower = dict_str.toLowerCase(); // to perform case insensitive match
            int index = 0;
            do{
                index = temp.indexOf(dict_str_lower,index);
                if(index != -1){
                    replacement_index.putIfAbsent(index,new String[]{dict.get(dict_str),dict_str});
                    index++;// to get the next match index of the same word in the string.
                }
            }while(index != -1 && index < temp.length());
        }

        StringBuilder res = new StringBuilder("");

        for(int i = 0;i < s.length(); ++i){
            if(replacement_index.containsKey(i)){
                res.append(replacement_index.get(i)[0]);
                i += replacement_index.get(i)[1].length() - 1;
            }else{
                res.append(s.charAt(i));
            }
        }

        return res.toString();
    }

}
  • 在上面的代码中,我们首先获取列表中的所有映射值,并按照长度的降序对它们进行排序

  • 我们这样做是为了避免上面解释的重叠问题,首先匹配较大的字符串,然后处理较小的字符串

  • 第二种方法是获取映射中值的所有匹配索引,并将它们存储在另一个映射中以获得最终结果

  • 第三,是按原样循环字符串,如果我们在映射中有迭代中的当前索引(更准确地说是在
    replacement\u index
    ),那么我们从映射中附加替换值,并将指针移动到大于替换长度的位置

注意:我假设重叠字符串意味着较小的字符串完全封装在较大的字符串中。对于像
be right back
right back to
这样的字符串,对于
I will will back to this
,您的帖子中没有定义缩写。我想
import java.util.*;
class Solution{
    public static void main(String[] args) {
        Map<String, String> dict = new HashMap<>();
        dict.put("be right back", "BRB");
        dict.put("be right there", "BRT");
        dict.put("be right later", "BRL");
        dict.put("be", "B");
        dict.put("be back soon","B back soon");
        dict.put("faster than light","FTL");
        dict.put("later", "L8R");

        String[] tests = {
            "I will be right there later",
            "I will be right there",
            "I will be there",
            "I will go right there",
            "I will be there later",
            "I am faster than you",
            "Never faster than light",
            "Faster than light today"
        };

        for(String test_case : tests){
            System.out.println(test_case + " => " + convert(test_case, dict));   
        }
    }

    public static String convert(String s, Map<String, String> dict) {

        List<String> dict_words = new ArrayList<>(dict.keySet());
        Map<Integer,String[]> replacement_index = new HashMap<>();

        Collections.sort(dict_words,new Comparator<String>(){
            public int compare(String s1,String s2){
                if(s1.length() == s2.length()) return 0; // order doesn't seem to matter for same length strings
                return s2.length() - s1.length(); // return bigger length string first
            }
        });

        String temp = s.toLowerCase(); // to perform case insensitive match
        for(String dict_str : dict_words){
            String dict_str_lower = dict_str.toLowerCase(); // to perform case insensitive match
            int index = 0;
            do{
                index = temp.indexOf(dict_str_lower,index);
                if(index != -1){
                    replacement_index.putIfAbsent(index,new String[]{dict.get(dict_str),dict_str});
                    index++;// to get the next match index of the same word in the string.
                }
            }while(index != -1 && index < temp.length());
        }

        StringBuilder res = new StringBuilder("");

        for(int i = 0;i < s.length(); ++i){
            if(replacement_index.containsKey(i)){
                res.append(replacement_index.get(i)[0]);
                i += replacement_index.get(i)[1].length() - 1;
            }else{
                res.append(s.charAt(i));
            }
        }

        return res.toString();
    }

}