1.原題:
https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping/submissions/
Given a string s formed by digits ('0' - '9') and '#' . We want to map s to English lowercase characters as follows:
- Characters (
'a'to'i')are represented by ('1'to'9') respectively. - Characters (
'j'to'z')are represented by ('10#'to'26#') respectively.
Return the string formed after mapping.
It's guaranteed that a unique mapping will always exist.
翻譯:
給一個string s,由一串陣列和‘#’組成,我們需要把其解碼成英語小字母,
Input: s = "10#11#12"
Output: "jkab"
解釋: "j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2".
2.解題思路:
這道題考驗的是你對string,char的理解,其實用java寫這個題很麻煩,因為Java的string類實在是很麻煩,但是我就當順便練手了,實際上推薦用C類語言去弄,因為C的string本身就是char的array,,,(當然了你可以宣告char array)
class Solution { public String freqAlphabets(String s) { String res =""; //初始化一個string類 for (int i = 0; i < s.length(); i++) { if ((i+2) < s.length() && s.charAt(i + 2) == '#')//向前搜索2個位置找#標志 { String tmp_1 = String.valueOf(s.charAt(i))+ String.valueOf(s.charAt(i+1)); int tmp_2 = Integer.parseInt(tmp_1); String tmp_3 = String.valueOf((char)('j' + tmp_2 - 10)); res += tmp_3; //#的數字肯定是大于10的,而且是從j開始,如果是10的話, i += 2; //10-10=0,這時候就是J,如果是11, 11-10=1,為j之后的k, } else { char tmp_4 = (char)((s.charAt(i) - '1') + 'a');//從0開始為a,以此類推, String tmp_3 = String.valueOf(tmp_4); res += tmp_3; } } return res; } }
參考閱讀:
1.Java 如何將String轉化為Int:https://blog.csdn.net/a772304419/article/details/79723249
2.Java charAt() 方法:https://www.runoob.com/java/java-string-charat.html
3.Java中char和String的相互轉換:https://www.cnblogs.com/rrttp/p/7922202.html
4.Char型別的加減法:https://blog.csdn.net/wz568780720/article/details/81612467
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/41080.html
標籤:其他
上一篇:我的2020年前幾天
