【问题标题】:How to solve one of this CodingBat java method?如何解决这种 CodingBat java 方法之一?
【发布时间】:2016-09-03 00:47:34
【问题描述】:

这是我的作业:

如果两个字符串不为空并且它们的第一个字符相同,我们会说它们“匹配”。循环然后返回给定的非空字符串数组,如下所示:如果字符串与数组中较早的字符串匹配,则交换数组中的 2 个字符串。当数组中的一个位置被交换时,它不再匹配任何东西。使用地图,只需通过数组一次即可解决此问题。

allSwap(["ab", "ac"]) → ["ac", "ab"]

allSwap(["ax", "bx", "cx", "cy", "by", "ay", "aaa", "azz"]) → ["ay", "by", "cy", "cx", "bx", "ax", "azz", "aaa"]

allSwap(["ax", "bx", "ay", "by", "ai", "aj", "bx", "by"]) → ["ay", "by", "ax", "bx", "aj", "ai", "by", "bx"]

【问题讨论】:

    标签: arrays hashmap


    【解决方案1】:

    在map中,存储第一个字母作为key,key的最近索引作为value。当地图中不存在字母时,将其添加到地图中。当地图中已经存在一个字母时,将其从地图中移除并与该索引交换。

    /**
     * Swaps strings in the array that have the same first letter,
     * reading left to right. Once a string has been swapped, 
     * it will not be swapped again. The input array will be mutated.
     * 
     * @param  strings the strings to perform swaps from
     * @return         the strings after swapping
     */
    public static String[] allSwap(final String[] strings) {
        // map of first characters, and the index where they were last seen
        final Map<Character, Integer> potentialSwap = new HashMap<>();
    
        for (int thisIndex = 0; thisIndex < strings.length; thisIndex++) {
            if (strings[thisIndex].isEmpty()) {
                continue; // skip empty strings
            }
    
            final Character firstChar = strings[thisIndex].charAt(0); // box charAt(0)
            // remove firstChar from the map. If it's not found, returns null
            final Integer potentialIndex = potentialSwap.remove(firstChar);
    
            if (potentialIndex != null) {
                final int thatIndex = potentialIndex; // unbox potentialIndex
                // swap values at thisIndex and thatIndex
                final String temp = strings[thatIndex];
                strings[thatIndex] = strings[thisIndex];
                strings[thisIndex] = temp;
            } else {
                // save the index for possible swapping later
                potentialSwap.put(firstChar, thisIndex); // box thisIndex
            }
        }
    
        return strings;
    }
    

    Ideone Demo

    【讨论】:

    • 这很有帮助,但我想知道当(a)这似乎是一个家庭作业问题,并且(b)OP 似乎没有做出任何事先努力时,可能会达到什么教育目的。如果他们交出这个解决方案,他们可能什么都没学到。
    • @halfer 在回答家庭作业问题时,我一直发现向某人展示好的代码是什么样子是一个巨大的好处。我无法知道他们之前是否进行过任何尝试,但我敢打赌,他们有,而且他们将成为一个体面的人,真正阅读代码,如果他们不理解某些内容,就会提出问题。跨度>
    • @halfer 当然我知道作业问题很容易被滥用,所以我努力只在算法相当复杂的情况下才回答,因为这意味着提问者的技能水平是合理的在语言方面,并根据成绩在学校取得了迄今为止的成绩。我不是来评判别人的,只是把我的知识付诸实践。学校的工作是测试他们是否学到了一些东西。
    • 好的,感谢您考虑周全的回复。你的善意可能会被浪费,因为我的经验是这样的问题甚至没有得到回应,但你的业力肯定会得到提升!
    • 感谢您的回复。这不是我的作业问题。我没有在顶部写“这是我的作业”。我是这个 stackoverflow 的新手,我认为它已经默认写在那里了。
    【解决方案2】:
    public String[] allSwap(String[] strings) {
    
        // map of first characters, and the index where they were last seen
         Map<Character, Integer> map = new HashMap();
    
        for (int i = 0; i < strings.length; i++) {
    
    
             char firstChar = strings[i].charAt(0); 
             // box charAt(0)
            // remove firstChar from the map. If it's not found, returns null
             Integer removedIndex = map.remove(firstChar);
    
            if (removedIndex != null) {
                 int j = removedIndex; 
                // unbox potentialIndex
                // swap values at thisIndex and thatIndex
                 String temp = strings[j];
                strings[j] = strings[i];
                strings[i] = temp;
            } else {
                // save the index for possible swapping later
                map.put(firstChar, i); 
            }
        }
    
        return strings;
    }
    

    【讨论】:

      【解决方案3】:

      这也可以!

       public String[] allSwap(String[] strings) {
            
            
            Map<String,Integer> map = new HashMap<String,Integer>();
            
            
            for(int i=0;i<strings.length;i++){
              
              if(!map.containsKey(strings[i].substring(0,1))){
                map.put(strings[i].substring(0,1),i);
              }
              else{
                String temp = strings[map.get(strings[i].substring(0,1))];
                strings[map.get(strings[i].substring(0,1))] = strings[i];
                strings[i] = temp;
                map.remove(strings[i].substring(0,1));
              }
              
            }
            
          return strings;
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-10
        • 1970-01-01
        • 2018-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多