for循环计算字符串中重复的字符数,然后删除重复的字符

时间:2014-03-27 16:55:39

标签: java string loops for-loop

示例:中午攻击= a3t3c1k1 2n2o2

它也算空间。 这就是我所拥有的,但它似乎没有正确地返回:

String getCount(String str) {
    String R = "";
    int l = S.length();
    int cnt = 1;

    for (int i = 0; i < l; i++)
        for (int j = i + 1; j < l; j++)
            if (S.charAt(j) == S.charAt(i)) {
                cnt++;
                R = R + S.charAt(i)+""+cnt;
                System.out.print(S.charAt(i) + cnt);
            }      
    return R;
}

6 个答案:

答案 0 :(得分:1)

如果字符串足够小,你不需要任何花哨的东西,只需强制它(对于attack at noon,它运行3ms)。

此代码将迭代所有字符,如果没有找到,它会将字符及其计数附加到StringBuilder,然后在终止之前打印。

import java.util.HashMap;

public class Counter {
    HashMap<String, Integer> counts;
    StringBuilder result;

    public static void main(String[] args) {
        Counter counter = new Counter();
        counter.countString("attack at noon");
    }

    void countString(String S) {
        counts = new HashMap<String, Integer>();
        result = new StringBuilder();

        String[] split = S.split("");
        for (int i = 1; i < split.length; i++) {
            String c = split[i];
            countChar(c, S);
        }
        System.out.println(result);
    }

    void countChar(String c, String s) {
        Integer integer = counts.get(c);
        if (integer == null) {
            int i = s.length() - s.replace(c, "").length();
            counts.put(c, i);
            result.append(c).append(i);
        }
    }
}

答案 1 :(得分:0)

你应该保留一个int[]来存储字母表中每个字母的数量。

private int[] getDuplicates(String string) {
  String str = string.toLowerCase();
  int[] charCounts = new int[27];
  for (int i = 0; i < str.length(); i++) {
    char c = str.charAt(i);
    if (c == ' ') {
      charCounts[26]++;
    }
    else {
      charCounts[c - 'a']++;
    }
  }

  return charCounts;
}

此方法将返回一个数组,其中第0个索引对应于次数&#39; a&#39;显示在你的字符串中

public String getCharCounts(String string) {
  int[] charCounts = getDuplicates(string);
  StringBuffer strBuff = new StringBuffer();
  for (int i = 0; i < charCounts.length; i++) {
    if (charCounts[i] > 0) {
      char c;
      if (i < 26) {
        c = (char)(i + (int)'a');
      }
      else {
        c = ' ';
      }
      strBuff.append(c);
      strBuff.append(charCounts[i]);
    }
  }
  return strBuff.toString();
}

此方法使用从第一个方法获得的数组,并附加字符后跟其计数。这样更有效,因为您只需要通过String一次获取计数,然后在数组中传递一次以制定重复数据删除的String。运行时间为O(n)

答案 2 :(得分:0)

使用LinkedHashMap存储每个字符的计数,因为它维护了插入顺序。

public static String countChars(String str) {
    Map<Character, Integer> map = new LinkedHashMap<Character, Integer>();
    for( char c : str.toCharArray() ) {
        if( map.containsKey( c ) ) {
            map.put( c, map.get( c ) + 1 );
        } else {
            map.put( c, 1 );
        }
    }
    StringBuilder sb = new StringBuilder();
    for( Character key : map.keySet() ) {
        sb.append(key.toString() + map.get( key ) );
    }
    return sb.toString();
}

答案 3 :(得分:0)

public static void main(String[] args) {
    System.out.println(getCount("attack at noon"));
}

String getCount(String str) {
        String R = "";
        String S = str;
        int l = S.length();
        int cnt;

        first:for (int i = 0; i < l; i++) { //Foreach letter
            cnt = 0;
            for (int j = i; j < l; j++) {

                if (S.charAt(j) == S.charAt(i)) {

                    if ( R.indexOf(S.charAt(j)) != -1 ) {
                        continue first;
                    }
                    cnt++;
                }
            }
            R = R + S.charAt(i) + cnt; 
        }
        return R;
    }
  

输出:a3t3c1k1 2n2o2

答案 4 :(得分:0)

这是我的企业级解决方案

attack at noon = a3t3c1k1 2n2o2

这是代码的另一个测试:

For loop that counts how many characters repeat in a string, 
then removes the repeated characters = 
f1o6r9 15l1p3t10h6a9c5u1n5s5w1m2y1e11i2g1,1v1d1

这是代码:

package com.ggl.testing;

import java.util.ArrayList;
import java.util.List;

public class Counter {

    private List<CharacterCount>    characterCounts;

    public Counter() {
        this.characterCounts = new ArrayList<CharacterCount>();
    }

    public void countString(String s) {
        s = s.toLowerCase();
        for (int i = 0; i < s.length(); i++) {
            CharacterCount cc = new CharacterCount(s.charAt(i));
            addCharacterCount(cc);
        }
    }

    private void addCharacterCount(CharacterCount cc) {
        for (CharacterCount count : characterCounts) {
            if (count.getCharacter() == cc.getCharacter()) {
                count.setCount(count.getCount() + 1);
                return;
            }
        }
        cc.setCount(1);
        characterCounts.add(cc);
    }

    public String returnString() {
        StringBuilder builder = new StringBuilder();
        for (CharacterCount count : characterCounts) {
            builder.append(count.getCharacter());
            builder.append(count.getCount());
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        String s = "For loop that counts how many characters " +
                "repeat in a string, then removes the repeated " +
                "characters";
        Counter counter = new Counter();
        counter.countString(s);
        System.out.println(s + " = " + counter.returnString());
    }

    public class CharacterCount {
        private char    character;
        private int     count;

        public CharacterCount(char character) {
            this.character = character;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

        public char getCharacter() {
            return character;
        }

    }
}

答案 5 :(得分:0)

使用Guava

String getGroup(final String string) {
      StringBuffer stringBuffer = new StringBuffer();
      for(char c : string.toCharArray()) {
          int occurances = CharMatcher.is(c).countIn(string);
          if (stringBuffer.indexOf(String.valueOf(c)) == -1) {
            stringBuffer.append(String.valueOf(c) + occurances);
          }
      }
      return stringBuffer.toString();
  }