题中要求不允许使用额外的存储结构,因此在这里用时间换空间,使用两个 for
循环,时间复杂度为 O(n*n)
。
import org.junit.Test; import static org.junit.Assert.assertEquals; public class Solution { public boolean checkDifferent(String iniString) { if (iniString.length() == 1 || iniString.length() == 0) return true; if (iniString.length() > 256) return false; for (int i = 0; i < iniString.length(); i++) { for (int j = i + 1; j < iniString.length(); j++) { if (iniString.charAt(i) == iniString.charAt(j)) return false; } } return true; } @Test public void testSolve() { assertEquals(checkDifferent(""), true); assertEquals(checkDifferent("aeiou"), true); assertEquals(checkDifferent("BarackObama"), false); assertEquals(checkDifferent("A"), true); } }