在字符串中查找第一个非重复字符

时间:2020-02-23 14:34:10  来源:igfitidea点击:

"我们将如何在字符串中找到第一个不重复字符。"

例如:如果输入字符串是"analogy",则程序应返回'n'如果输入字符串是"最简单的",则程序应返回'a'

第一个方法:

我们将使用LinkedHashMap在字符串中找到第一个非重复字符。

算法:

  • 在循环字符串时获取字符
  • 在LinkedHashMap中将此字符置于Count。如果字符已经存在,则增加1.
  • 在迭代时从linkedhashmap获取计数。如果计数为1,则将该字符返回为linkedhashmap维护插入顺序。

程序:

package org.igi.theitroad.algo;
 
import java.text.*;
import java.util.*;
import java.util.Map.Entry;
 
public class GetFirstNonRepeatingCharacterMain {
 public static void main(String[] args) {
  System.out
    .println("First non repeated character for String analogy is : "
      + getNonRepeatedCharacter("analogy"));
  System.out
    .println("First non repeated character for String easiest is : "
      + getNonRepeatedCharacter("easiest"));
 }
 
 public static Character getNonRepeatedCharacter(String str) {
  Map<Character, Integer> countCharacters = new LinkedHashMap<Character, Integer>();
  for (int i = 0; i < str.length() - 1; i++) {
   Character c = str.charAt(i);
   if (!countCharacters.containsKey(c)) {
    countCharacters.put(c, 1);
   } else {
    countCharacters.put(c, countCharacters.get(c) + 1);
   }
  }
  //As LinkedHashMap maintains insertion order, first character with
  //count 1 should return first non repeated character
  for (Entry<Character, Integer> e : countCharacters.entrySet()) {
   if (e.getValue() == 1)
    return e.getKey();
 
  }
  return null;
 
 }
}

运行上面的程序时,我们将获取以下输出:

First non repeated character for String analogy is : n
First non repeated character for String easiest is : a

第二种方法:

算法:

  • 迭代串的每个字符。
  • 如果LastIndexof和indexof返回相同的值,则它是字符串中的第一个非重复字符。

程序:

package org.igi.theitroad.algo
public class GetFirstNonRepeatingCharacterMain
{
 public static void main(String[] args)
 {
        System.out.println("First non repeated character for String analogy is : "+getNonRepeatedCharacter("analogy"));
        System.out.println("First non repeated character for String easiest is : "+getNonRepeatedCharacter("easiest"));
 }
 public static Character getNonRepeatedCharacter(String str)
 {     char charaaray[]=str.toCharArray();
       for (int i=0; i<str.length();i++)
      {
          if (str.lastIndexOf(charaaray[i]) == str.indexOf(charaaray[i]))
               return charaaray[i];
      }
  return null;
 }
}

运行上面的程序时,我们将获取以下输出:

First non repeated character for String analogy is : n
First non repeated character for String easiest is : a