java如何使得的一串類似wwwiiinnnwwwnnniii等的字符串如win這樣的順序輸出,三個字母個數不同沒關係?

這是我幾天前去公司的筆試題目,當時想的不太清楚,所以沒具體寫出來,只是用語言描述了一下,下面我將貼出我的方法,如果大家有什麼更好的方法別忘記分享出來哦;

public static void main(String[] args) {
		/**/
		String str="wwiiiwwiinnn";
		String[] strs = str.split("");
		int a=0,b=0,c=0;
		int temp=0;
		for(String st:strs){
			if(st.equals("w")){
				a++;
			}
			if(st.equals("i")){
				b++;
			}
			if(st.equals("n")){
				c++;
			}
			temp=a > b ? (a > c ? a : c) : b > c ? b : c;
		}
		for(int i=0;i<temp;i++){
			if(a>0){
				System.out.print("w");
				a--;
			}
			if(b>0){
				System.out.print("i");
				b--;
			}
			if(c>0){
				System.out.print("n");
				c--;
			}
		}
	}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章