package com.houning;
public class Driver
{
public static void main(String[] args)
{
String s = "regbavcdbbsahha";
System.out.println(Driver.getFirstAndMost(s));
}
public static char getFirstAndMost(String str)
{
if(null != str)
{
int mostNum[] = new int[128];
int firstIdx [] = new int[128];
int num = str.length();
for (int i = 0; i < firstIdx.length; i++)
{
firstIdx[i] = num;
}
for (int i = 0; i < str.length(); i++)
{
//字母所在的位置出现在次数依次增加
mostNum[str.charAt(i)]++;
//找出每一个字母出现的第一次的坐标位置
if(i < firstIdx[str.charAt(i)])
{
firstIdx[str.charAt(i)] = i;
}
}
int mostChar = 0;
for (int i = 0; i < firstIdx.length; i++)
{
if(mostNum[i] < 1)
continue;
if(mostNum[i] > mostNum[mostChar])
{
mostChar = i;
}
else if ((mostNum[i] == mostNum[mostChar])
&& (firstIdx[i] < firstIdx[mostChar]))
{
mostChar = i;
}
}
return (char)mostChar;
}
else
{
return '\0';
}
}
}
public class Driver
{
public static void main(String[] args)
{
String s = "regbavcdbbsahha";
System.out.println(Driver.getFirstAndMost(s));
}
public static char getFirstAndMost(String str)
{
if(null != str)
{
int mostNum[] = new int[128];
int firstIdx [] = new int[128];
int num = str.length();
for (int i = 0; i < firstIdx.length; i++)
{
firstIdx[i] = num;
}
for (int i = 0; i < str.length(); i++)
{
//字母所在的位置出现在次数依次增加
mostNum[str.charAt(i)]++;
//找出每一个字母出现的第一次的坐标位置
if(i < firstIdx[str.charAt(i)])
{
firstIdx[str.charAt(i)] = i;
}
}
int mostChar = 0;
for (int i = 0; i < firstIdx.length; i++)
{
if(mostNum[i] < 1)
continue;
if(mostNum[i] > mostNum[mostChar])
{
mostChar = i;
}
else if ((mostNum[i] == mostNum[mostChar])
&& (firstIdx[i] < firstIdx[mostChar]))
{
mostChar = i;
}
}
return (char)mostChar;
}
else
{
return '\0';
}
}
}